您的位置:首页 > 其它

排序 - 选择法

2015-07-03 20:52 267 查看
选择法

基本思想,

每一趟 (例如第 i 趟,i = 0, 1, …,n-2)在后面 n-i个待排的数据元素中选出关键字

最小的元素, 作为有序元素序列的第 i 个元素。

排序过程

首先通过n-1次关键字比较,从n个记录中找出关键字最小的记录,将它与第一个记录交换;

再通过n-2次比较,从剩余的n-1个记录中找出关键字次小的记录,将它与第二个记录交换;

重复上述操作,共进行n-1趟排序后,排序结束。

时间复杂度O(n^2)





代码:

#include <iostream>
#include <cstdio>
#include <ctime>
#include <iomanip>
using namespace std;

int arr[10000];

void mySwap(int &a, int &b)
{
int t = a;
a = b;
b = t;
}

void selectSort(int *a, int len)
{
for (int i = 0; i < len; i++) {
int k = i; // 记录最小的位置
for (int j = i + 1; j < len; j++) {
if (a[j] < a[k]) {
k = j;
}
}
if (k != i) {
mySwap(a[i], a[k]);
}
}
}

void printArray(int *a, int len)
{
for (int i = 0; i < len; i++) {
if (i != 0 && i % 10 == 0) {
cout << endl;
}
cout << setw(3) << a[i] << ' ';
}
cout << endl;
}

int main()
{
srand(time(0));
cout << "Please input length of array: ";
int len;
cin >> len;
for (int i = 0; i < len; i++) {
arr[i] = rand() % 100;
}
cout << "Before sorting:\n";
printArray(arr, len);
selectSort(arr, len);
cout << "After sorting:\n";
printArray(arr, len);

return 0;
}

/*
Please input length of array: 20
Before sorting:
3  28  35  97  87   7  33  60  84  47
18  71  94  68  54  94  30   8  95  31
After sorting:
3   7   8  18  28  30  31  33  35  47
54  60  68  71  84  87  94  94  95  97
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: