排序算法(sorting algorithm) 之 选择排序(selection sort)
https://en.wikipedia.org/wiki/Selection_sort
loop1:
4,6,1,3,7 -> 4,6,1,3,7
4,6,1,3,7 -> 1,6,4,3,7
1,6,4,3,7 -> 1,6,4,3,7
1,6,4,3,7 -> 1,6,4,3,7
loop2:
1,6,4,3,7 -> 1,4,6,3,7
1,4,6,3,7 -> 1,3,6,4,7
1,3,6,4,7 -> 1,3,6,4,7
loop3:
1,3,6,4,7 -> 1,3,4,6,7
1,3,4,6,7 -> 1,3,4,6,7
loop4:
1,3,4,6,7 -> 1,3,4,6,7
package sorting; import java.util.Arrays; import org.junit.Test; public class SelectionSorting { int[] items = { 4, 6, 1, 3, 7 }; int step = 0; // ① 相邻 // ② 差一步 // ③ n个数可产生 n-1 对 // ④ 逐块收复失地 @Test public void sort() { for (int i = 0; i < items.length - 1; i++) { for (int j = i + 1; j < items.length; j++) { step++; if (items[i] > items[j]) { swap(i, j); } } } System.out.println(step + ":" + Arrays.toString(items)); } public void swap(int i, int j) { int backup = items[i]; items[i] = items[j]; items[j] = backup; } }
20230307 重写感触:冒泡是相邻发生交换,选择还包含非相邻
public static void main(String[] args) { int[] arr = new int[] { 4, 6, 1, 3, 7 }; select(arr, "asc"); for (int i : arr) { System.out.println(i); } } /** * 选择排序 * * @param arr * @param flag */ public static void select(int[] arr, String flag) { boolean asc = "asc".equalsIgnoreCase(flag); for (int j = 0; j < arr.length - 1; j++) { for (int i = j + 1; i < arr.length; i++) { int a = arr[j]; int b = arr[i]; if (asc ? a > b : a < b) { arr[j] = b; arr[i] = a; } } } }