Selection sort
The selection sort algorithm sorts an array by repeatedly finding the maximum element (considering ascending order) from unsorted part and putting it at the end. The algorithm maintains two subarrays in a given array.
- The subarray which is already sorted.
- Remaining subarray which is unsorted.
In every iteration of selection sort, the maximum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.
Following example explains the above steps:
public class Study {
/**
* main function to sort array using selection sort
*
* @param args
*/
public static void main(String[] args) {
int[] arr = {1, -10, -2, 3, 8, 100, -100, 2, 6, 25};
print(arr);
System.out.println();
selectionAsc(arr);
// selectionDes(arr);
print(arr);
}
/**
* ascending order
*
* @param arr
*/
private static void selectionAsc(int[] arr) {
/*
lastUnsortedIndex means the last index of the unsorted array, the original value is arr.length-1
since the input array is unsorted at beginning
*/
int lastUnsortedIndex = arr.length - 1;
while (lastUnsortedIndex > 0) {
int largest = 0;
// each loop we find the maximum element index i from 0 to lastUnsortedIndex
for (int i = 0; i <= lastUnsortedIndex; i++) {
if (arr[i] > arr[largest]) largest = i; // update the maximum element's index
}
swap(arr, largest, lastUnsortedIndex);
lastUnsortedIndex--;
}
}
/**
* descending order
*
* @param arr
*/
private static void selectionDes(int[] arr) {
int lastUnsortedIndex = arr.length - 1;
while (lastUnsortedIndex > 0) {
int smallest = 0;
for (int i = 0; i <= lastUnsortedIndex; i++) {
if (arr[i] < arr[smallest]) smallest = i;
}
swap(arr, smallest, lastUnsortedIndex);
lastUnsortedIndex--;
}
}
/**
* swap values
*
* @param arr
* @param i
* @param j
*/
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/**
* print the array
*
* @param arr
*/
private static void print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print("arr[" + i + "] = " + arr[i] + " ");
}
}
}
Result
arr[0] = 1 arr[1] = -10 arr[2] = -2 arr[3] = 3 arr[4] = 8 arr[5] = 100 arr[6] = -100 arr[7] = 2 arr[8] = 6 arr[9] = 25
arr[0] = -100 arr[1] = -10 arr[2] = -2 arr[3] = 1 arr[4] = 2 arr[5] = 3 arr[6] = 6 arr[7] = 8 arr[8] = 25 arr[9] = 100