排序算法(sorting algorithm) 之 选择排序(selection sort)

时间:2024-04-29 19:06:16

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,,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,,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;
} }