Selection Sort
Selection sort divides the array into sorted and unsorted parts. It repeatedly selects the smallest element from the unsorted part and swaps it with the first unsorted element. Time complexity: O(n²) in all cases. It is not stable but is in-place.
Java implementation:
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) minIdx = j;
}
swap(arr, i, minIdx);
}
}
Two Minute Drill
- Selection sort finds minimum in unsorted part and swaps.
- Always O(n²) time, O(1) space.
- Not stable (swapping can change order of equal elements).
- Performs fewer swaps than bubble sort.
Need more clarification?
Drop us an email at career@quipoinfotech.com
