Selection sort algorithm sorts an unsorted array by repeatedly finding the minimum element and placing it to the beginning of the array.
arr[] = 23 54 2 52 31
//Find minimum element and swap it to the start of array [0..4]
2 54 23 52 31
//Now from the rest of the unsorted array, find minimum element [1..4]
//and place it to the beginning of array [1..4]
2 23 54 52 31
//Now from the rest of the unsorted array, find minimum element [2..4]
//and place it to the beginning of array [2..4]
2 23 31 54 52
//Now from the rest of the unsorted array, find minimum element [3..4]
//and place it to the beginning of array [3..4]
2 23 31 52 54
void selectionSort(int arr[], int n){
int min_index;
bool swap_i = false;
for(int i=0; i<n-1; i-1){
min_index = i;
//Find minimum element in rest of the unsorted array
for(int j=min_index+1; j<n; j++){
if(arr[j] < arr[min_index]){
min_index = j;
swap_i = true;
}
}
if(swap_i){
//Swap minimum found index with the start of the array
swap(&arr[i], &arr[min_index]);
}
else{
break;
}
swap = false;
}
}