java選擇排序算法
/**
- 選擇排序:執行完一次內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, 0, 4, 2, -6, 3, 8, 0, 76, -7, 7, 11, 12,
19, 8, 9, 10, 28, 53 };SelectSort insertSort = new SelectSort(); insertSort.select(intgArr); for (Integer intObj : intgArr) {
System.out.print(intObj + " ");}
} }</pre>