选择排序:大致思路是找出第i小的数字,并与原数组中第i位置的数字交换位置。循环N-1次,每次循环N-i-1次比较。
时间复杂度O(n^2);空间复杂度O(1);
图示:
C++版本源代码:
// selection sort 选择排序
#include <iostream>
using namespace std;
void selectionSort(int num[],int len){
int smallest;
for(int i = 0;i < len-1;i++){
smallest = i;
for(int j = i + 1;j < len;j++){
//smallest = i;
if(num[smallest] > num[j]){
smallest = j;
}
//swap(num[smallest],num[i]);
}
swap(num[smallest],num[i]);
}
for(int i = 0;i < len;i++){
cout << num[i] << " ";
}
cout << endl;
}
void swap(int &a,int &b){
int temp;
temp = a;
a = b;
b = temp;
}
int main(){
int num[] = {23,65,25,27,68,20,45,36,123,685,526,1,34,54,76,23,87,4565,231,43536};
int len = sizeof(num)/sizeof(num[0]);
cout << "Before sort:";
for(int i = 0;i < len;i++){
cout << num[i] << " ";
}
cout << endl;
cout << "After sort:";
selectionSort(num,len);
return 0;
}
}
结果: