Selection Sort
- Categories Java, Arrays in Java
What is selection sort?
Selection sort is an in-place
comparison-based algorithm. It divides the list into two parts, the sorted part
on the left and the unsorted part on the right. It works by repeatedly finding
the minimum element from the unsorted part and putting it the sorted part.
There are many sorting algorithms like quicksort, timsort, or merge sort which are actually more popular and efficient. Selection sort is not suitable for large data sets as it has average performance.
To continue learning, please see the video on our channel: https://youtu.be/nVz7efKXscY
Pseudo code:
START
Take an array or list of size n in list
FOR i = 0 TO i < (n-1) // Loop for the pass
int min= i;
FOR j = i+1 TO j < n // Loop for the comparison
IF list[j] < list[min]
min = j;
END IF
END FOR
swap list[i], list[min]
END FOR
END
JAVA code:
void selection(int [] list,int n) {
for (int i = 0; i < n-1; i++) {
int min = i; // Assume I = minimum element
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min])
min = j;
// Swap the minimum element with ith element
int temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
}