選擇排序
基本思想:
- 從左到右遍歷數組,找出最小/大的放在左側與left所標誌的位置交換元素,即第一次將數組中最小(或者最大)的元素置頂(數組下標爲0的位置);
- 然後從此數組下標爲0的位置向右找最小(或者最大)的元素與下標爲1的位置交換,以此類推
複雜度
最差情況:
進行比較操作的時間複雜度爲O(n^2),進行移動操作的時間複雜度爲O(n)
選擇排序是不穩定的排序算法
代碼:
使用了單例模式,方便在程序內部比較不同算法的移動/比較次數,不需要的刪掉就可以
代碼中in_order(List list, boolean flag)方法中的list爲一個ArryList,flag=true的時候按正序排列,flag=false的時候逆序排列
public class Selection_sort {
public static Selection_sort selection_sort;
private Selection_sort(){}
private int com_step;
private int move_step;
public int getCom_step() {
return com_step;
}
public int getMove_step() {
return move_step;
}
public static Selection_sort getSelection_sort(){
if(selection_sort==null){
synchronized (Insert_sort.class){
if(selection_sort==null){
selection_sort=new Selection_sort();
}
}
}
return selection_sort;
}
public List<Integer> in_order(List<Integer> list, boolean flag) throws IOException {
com_step=0;
move_step=0;
Integer[] nums=list.toArray(new Integer[0]);//將列表list轉爲Integer對象數組
if(flag==true){
int min;
for (int i = 0; i < nums.length; i++) {
min = i;
for (int j = i+1; j < nums.length; j++) {
com_step++;
if(nums[min] > nums[j]) {
min = j;
}
}
if(min != i) {
move_step+=3;
swap(nums, i, min);
}
}
}
else {
int max;
for (int i = 0; i < nums.length; i++) {
max = i;
for (int j = i+1; j < nums.length; j++) {
com_step++;
if(nums[max] < nums[j]) {
max= j;
}
}
if(max != i) {
move_step+=3;
swap(nums, i, max);
}
}
}
list=new ArrayList<>(Arrays.asList(nums));
return list;
}
public void swap(Integer[] tem, int i, int j) {
int temp = tem[i];
tem[i] = tem[j];
tem[j] = temp;
}
}