Alg.7 Selection Sort

From algoexpert.io

Selection Sort is pretty much like the Insertion Sort. We divide the original array into two parts, “ordered” and “disordered”. But for Selection Sort, we will find the smallest number in the “disordered” part, and insert that number into “ordered” one. That’s why we called it Selection Sort.

1
2
3
4
5
6
7
8
9
10
11
public static int[] selectionSort(int[] array) {
// Write your code here.
for (int i = 0; i < array.length - 1; i++){
int minIndex = i;
for (int j = i; j < array.length; j++) {
if (array[j] < array[minIndex]) minIndex = j;
}
swap(array, i, minIndex);
}
return array;
}

Time complexity: O(n^2); Space complexity: O(1)

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2019-2021 Zirun Lin

Thanks~

支付宝
微信