您的位置:首页 > 编程语言 > Java开发

Java系列-排序算法之选择排序

2017-05-11 10:22 615 查看
一句话概括思想: 从无序数组中选出当前最小值交换放入数组的第1-n位,最终排序结束则成为有序组。

话不多说,直接上代码:

public static void main(String[] args) {
//the original array
int[] arrSource = {10, 3, 4, 7, 22, 456};
//sort the array
selectedSort(arrSource);
//print the elements of array
for (int element : arrSource
) {
System.out.println(element);
}
}

private static void selectedSort(int[] arrSource) {
//ifn, return
if (arrSource == null || arrSource.length == 0) {
return;
}
//record the index of Mimimum
int minIndex = 0;
//sorted array
for (int i = 0; i < arrSource.length - 1; i++) {
minIndex = i;
for (int j = i + 1; j < arrSource.length; j++) {
//if arrSource[i] > arrSource[j], record the index of arrSource[j]
if (arrSource[minIndex] > arrSource[j]) {
minIndex = j;
}
}
//if the mimimum is not the initial value, then swap them
if (i != minIndex) {
swap(arrSource, i, minIndex);
}
}
}

private static void swap(int[] arr, int i, int i1) {
int temp = arr[i];
arr[i] = arr[i1];
arr[i1] = temp;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java 排序算法