Selection Sort in Java

Selection sort in Java is used to sort the unsorted values in an array. In selection sorting algorithm, the minimum value in an array is swapped to the very first position in that array.

Selection Sort in Java

Selection sort in Java is used to sort the unsorted values in an array. In selection sorting algorithm, the minimum value in an array is swapped to the very first position in that array.

Selection Sort in Java

Selection sort in Java is used to sort the unsorted values in an array. In selection sorting algorithm, the minimum value in an array is swapped to the very first position in that array. In the next step the first value of array is left and minimum element from the rest of the array is swapped to second position. This procedure is repeated till the array is sorted completely.

Selection sort is probably the most spontaneous sorting algorithm. Selection sort is simple and more efficient when it comes to more complex arrays.

The complexity of selection sort in worst-case is Θ(n2), in average-case is Θ(n2), and in best-case is Θ(n2).

Following example shows the selection sort in Java.

In selection sort algorithm, first assign minimum index in key as index_of_min=a. Then the minimum value is searched. Index of minimum value in key is assigned as index_of_min=b. Minimum value and the value of minimum index are then swapped.

In the next step the first element (value) is left, and remaining values are sorted by following same steps. This process is repeated till the whole list is sorted.

Example of Selection Sort in Java:

public class selectionSort{
public static void main(String a[]){
int i;
int array[] = {15, 67, 40, 92, 23, 7, 77, 12};
System.out.println("\n\n RoseIndia\n\n");
System.out.println(" Selection Sort\n\n"); 
System.out.println("Values Before the sort:\n"); 
for(i = 0; i < array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
selection_srt(array, array.length); 
System.out.print("Values after the sort:\n");  
for(i = 0; i <array.length; i++)
System.out.print(array[i]+" ");
System.out.println();
System.out.println("PAUSE");
}
public static void selection_srt(int array[], int n){
for(int x=0; x<n; x++){
int index_of_min = x;
for(int y=x; y<n; y++){
if(array[index_of_min]<array[y]){
index_of_min = y;
}
}
int temp = array[x];
array[x] = array[index_of_min];
array[index_of_min] = temp;
}
}
}

Output:

C:\array\sorting>javac selectionSort.java
C:\array\sorting>java selectionSort
RoseIndia
Selection Sort

Values Before the sort:
15 67 40 92 23 7 77 12

Values after the sort:
7 12 15 23 40 67 77 92