package com.shan.selectionSort;
/**
*
* @author shan
*选择排序:假设要按升序排列一个数列,
*选择排序先找到数列中最小的数,然后将它放到数列的最前面
*在剩下的数中找到最小的数,放在第一个数的后面,
*以此类推,知道数列中仅剩一个数为止。
*/
public class SelectionSort {
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length; i++) {
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
//both of them need to be record
currentMin = list[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
//take care the sequence
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
public static void main(String[] args) {
double[] list = { 1, 9, 4.5, 6.6, 5.7, -4.5 };
SelectionSort.selectionSort(list);
for (int i = 0; i < list.length; i++) {
System.out.print(list[i] + " ");
}
}
}
选择排序(Java语言实现)
最新推荐文章于 2022-04-12 20:55:49 发布