提交 cee2e5d0 编写于 作者: W WalterWen

选择排序

上级 78c0aca5
package com.we.sort;
public class SelectionSort {
public void selectionSort(int[] list) {
// 总共要经过 N-1 轮比较
for (int i = 0; i < list.length - 1; i++) {
int min = i;
// 每轮需要比较的次数 N-i
for (int j = i + 1; j < list.length; j++) {
if (list[j] < list[min]) {
// 记录目前能找到的最小值元素的下标
min = j;
}
}
// 将找到的最小值和i位置所在的值进行交换
if (i != min) {
int tmp = list[i];
list[i] = list[min];
list[min] = tmp;
}
System.out.format("第 %d 趟: ", i);
printAll(list);
}
}
// 打印完整序列
public void printAll(int[] list) {
for (int value : list) {
System.out.print(value + " ");
}
System.out.println();
}
public static void main(String[] args) {
int array[] = {3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48};
// 调用冒泡排序方法
SelectionSort bubble = new SelectionSort();
System.out.print("排序前: ");
bubble.printAll(array);
bubble.selectionSort(array);
System.out.print("排序后: ");
bubble.printAll(array);
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册