- 基本思想:
排序算法系列之選擇排序,將待排序的序列分成兩個部分,已排序和帶排序,每一趟從待排序的元素當中選出最值(最大值或者最小值)的一個元素,順序的放在已排序的數列最後,如此循環,直到全部待排序的數據元素排列完成。
2.基本代碼實現:
/**
* 簡單選擇排序:執行完一次內for循環後最小的一個數放在了數組的最前面。
*/
public class SelectSort {
/**
* 排序算法的實現,對數組中指定的元素進行排序
* @param array 待排序的數組
* @param from 從哪裏開始排序
* @param end 排到哪裏
* @param c 比較器
*/
public void select(Integer[] array) {
int minIndex;//最小索引
/*
* 循環整個數組(其實這裏的上界爲 array.length - 1 即可,因爲當 i= array.length-1
* 時,最後一個元素就已是最大的了,如果爲array.length時,內層循環將不再循環),每輪假設
* 第一個元素爲最小元素,如果從第一元素後能選出比第一個元素更小元素,則讓讓最小元素與第一
* 個元素交換
*/
for (int i=0; i<array.length; i++) {
minIndex = i;//假設每輪第一個元素爲最小元素
//從假設的最小元素的下一元素開始循環
for (int j=i+1;j<array.length; j++) {
//如果發現有比當前array[smallIndex]更小元素,則記下該元素的索引於smallIndex中
if ((array[j].compareTo(array[minIndex])) < 0) {
minIndex = j;
}
}
//先前只是記錄最小元素索引,當最小元素索引確定後,再與每輪的第一個元素交換
swap(array, i, minIndex);
}
}
public static void swap(Integer[] intgArr,int x,int y){
//Integer temp; //這個也行
int temp;
temp=intgArr[x];
intgArr[x]=intgArr[y];
intgArr[y]=temp;
}
/**
* 測試
* @param args
*/
public static void main(String[] args) {
Integer[] intgArr = { 5, 9, 1, 4, 2, 6, 3, 8, 0, 7 };
SelectSort insertSort = new SelectSort();
insertSort.select(intgArr);
for(Integer intObj:intgArr){
System.out.print(intObj + " ");
}
}
}