算法之选择排序代码参考
/**
* 选择排序
*
* @author zhang
*
*/
public class SelectSort {
public static void main(String[] args) {
int[] arr = new int[] { 1, 9, 2, 0, 5, 6, 5, 9, 5, 7, 3, 7 };
SelectSortMethod(arr);
System.out.println(Arrays.toString(arr));
}
public static void SelectSortMethod(int[] arr) {
// 遍历所有的数
for (int i = 0; i < arr.length; i++) {
// 假设当前i是最小的
int minIndex = i;
// 将当前所有的数和后面的数 依次比较,找到最小的数,并记录下标
for (int j = i + 1; j < arr.length; j++) {
// 如果后面的数,比假设记录的最小值小
if (arr[j] < arr[minIndex]) {
// 记录最小的下标
minIndex = j;
}
}
// 如果最小的数和当前遍历的数下标不一致,说明下标为min的数比当前遍历的数更小
if (i != minIndex) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
}

被折叠的 条评论
为什么被折叠?



