java版本選擇排序算法

選擇排序(Selection sort)是一種簡單直觀的排序算法。它的工作原理是每一次從待排序的數據元素中選出最小(或最大)的一個元素,存放在序列的起始位置,直到全部待排序的數據元素排完。 選擇排序是不穩定的排序方法(比如序列[5, 5, 3]第一次就將第一個[5]與[3]交換,導致第一個5挪動到第二個5後面)。

/**

* @param a

*/

public static void selectSort(int[] a) {

int length = a.length;

for (int i = 0; i < length; i++) {

int minIndex = i;

for (int j = i + 1; j < a.length; j++) {

if (a[j] < a[minIndex]) {

minIndex = j;

}

}

if (minIndex != i) {

int temp = a[minIndex];

a[minIndex] = a[i];

a[i] = temp;

}

}

}


分享到:


相關文章: