Wednesday, 28 August 2013

Selection Sort

Selection sort is a sorting algorithm, specifically an in-place comparison sort.

The algorithm works as follows:
1) Find the minimum value in the list.
2) Swap it with the value in the first position.
3) Repeat the steps above for the remainder of the list (starting at the second position and advancing each time).

Ex: Given array : 64 25 12 22 11
  After first step : 11 25 12 22 64
   After Second Step : 11 12 25 22 64
  After third step : 11 12 22 25 64
  After fourth step : 11 12 22 25 64

Implementation

class SelectionSort{
//method for selection sort
public static void selectionSort(int []a,int size){
int min;

for(int i = 0; i < size-1; i++){
min = i;
for(int j = i+1; j < size; j++){
if(a[min] > a[j]){
min = j;   //find the index of minimum value
}
}
if(min != i)
swap(a, i, min);
}
}

//Utility function to swap the elements in array
public static void swap(int []a, int i, int j){
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}

public static void main(String []args){
int a[] = {5,1, 4, 2, 8};

selectionSort(a, a.length);
System.out.println("elements of array after sorting..."+java.util.Arrays.toString(a));
}
}

No comments:

Post a Comment