其实在日常编程中,选择排序的应用场景是很少或者说几乎没有的,就是因为它的时间复杂度相对比较高O(N2),比起快速排序来说性能消耗较大,不过面对数据量不大的情况下,也是一种思路简单可行的排序方式,话不多说,我们先介绍下实现选择排序需要的数据结构:
列表两个,一个是待排序的原数据,另外一个是等大的空列表用于存储排序后的数据。
然后是基本原理:
1.查找出最大的元素,将元素从原列表中移除,并添加到用来排序的列表中
2.依次循环操作1,直至原列表为空停止.
代码实现(Java版):
private List<Integer> chooseSort(List<Integer> source) {
List<Integer> sortedList = new ArrayList<>();
int length = source.size();
for (int i = 0; i < length; i++) {
int maxIndex = getMaxIndex(source);
sortedList.add(source.remove(maxIndex));
}
return sortedList;
}
private int getMaxIndex(List<Integer> source) {
if (source == null || source.size() == 0) {
return -1;
}
//初始化值
int maxValue = source.get(0);
int maxIndex = 0;
for (int i = 0; i < source.size(); i++) {
if (source.get(i) > maxValue) {
maxValue = source.get(i);
maxIndex = i;
}
}
return maxIndex;
}
@Test
public void testSort() {
List<Integer> source = new ArrayList<>();
source.add(1);
source.add(4);
source.add(23);
source.add(2);
source.add(45);
source.add(12);
List<Integer> list = chooseSort(source);
list.forEach(integer -> System.out.println(integer));
}
输出结果为:45 23 12 4 2 1,符合预期。