选择排序
程序员文章站
2022-05-20 21:34:46
...
1.算法定义
第i趟排序从(elem[i],elem[i+1],...,elem[n-1])中选择最小的元素放到i这个位置上
2.示例
int str={1,8,3,5,9,15,8,18}
第一趟结果:1,8,3,5,9,15,8,18
第二趟结果:1,3,8,5,9,15,8,18
以此类推,每次从(elem[i],...elem[n-1])中选最小的元素放到elem[i]上
3.java实现
public class SelectionSort {
public static <T extends Comparable<T>> T[] selectionSort(T[] elements) {
for (int i = 0; i < elements.length - 1; i++) {
T min = elements[i];
for (int j = i + 1; j < elements.length; j++) {
if (min.compareTo(elements[j]) > 0) {
min = elements[j];
}
}
elements[i] = min;
}
return elements;
}
public static void main(String[] args) {
Integer[] elements = {1, 8, 3, 5, 9, 15, 8, 18};
elements = selectionSort(elements);
for (int i = 0; i < elements.length; i++) {
System.out.println(elements[i]);
}
}
}