tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Data Structures > Sort > Selection Sort

Selection Sort 

The following example shows selection sort implementation.

  • Best case time complexity of selection sort is O(n2)
  • Worst case time complexity of selection sort is O(n2)
  • Average case time complexity of selection sort is O(n2)

File Name  :  
com/bethecoder/tutorials/ds/sort/SelectionSort.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.ds.sort;

import java.util.Arrays;

public class SelectionSort {

  /**
   @param args
   */
  public static void main(String[] args) {

    int[] list = 651839402};
    System.out.println("Before sort : " + Arrays.toString(list));
    double timeTaken = selectionSortTimeTaken(list);
    System.out.println("After sort : " + Arrays.toString(list));
    System.out.println("Time taken for SelectionSort : " + timeTaken + " milliseconds.");
  }

  /**
   * In each iteration find the minimum element and swap with 
   * first element in the list. Repeat the same process with
   * next element until there are no more elements.
   
   @param list
   */
  public static void selectionSort(int[] list) {
    
    int min = 0;
    for (int i = ; i < list.length - ; i ++) {
      min = i;
      for (int j = i + ; j < list.length ; j ++) {
        if (list[j< list[min]) {
          min = j;
        }
      }
      list[i= list[i+ list[min(list[min= list[i]);
      System.out.println("Step " (i+1" : " + Arrays.toString(list));
    }
  }

  /**
   * Sorts and returns the time taken in milliseconds.
   
   @param list
   @return
   */
  public static double selectionSortTimeTaken(int[] list) {
    long startTime = System.nanoTime();
    selectionSort(list);
    long timeTaken = System.nanoTime() - startTime;
    return timeTaken * Math.pow(10, -6);
  }
}
   

It gives the following output,
Before sort : [6, 5, 1, 8, 3, 9, 4, 0, 2, 7]
Step 1 : [0, 5, 1, 8, 3, 9, 4, 6, 2, 7]
Step 2 : [0, 1, 5, 8, 3, 9, 4, 6, 2, 7]
Step 3 : [0, 1, 2, 8, 3, 9, 4, 6, 5, 7]
Step 4 : [0, 1, 2, 3, 8, 9, 4, 6, 5, 7]
Step 5 : [0, 1, 2, 3, 4, 9, 8, 6, 5, 7]
Step 6 : [0, 1, 2, 3, 4, 5, 8, 6, 9, 7]
Step 7 : [0, 1, 2, 3, 4, 5, 6, 8, 9, 7]
Step 8 : [0, 1, 2, 3, 4, 5, 6, 7, 9, 8]
Step 9 : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
After sort : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Time taken for SelectionSort : 0.397537 milliseconds.


                    Print

   



Books Recommendation

 
 
bl  br