您的位置:首页 > 其它

算法导论——2.1-2选择排序

2016-12-19 20:07 197 查看
题目:考虑排序存储在数组A中的n个数:首先找出A中的最小元素并将其和A[1]中的元素交换。接着,次大值和A[2]交换。以此类推。

#include<iostream>

using namespace std;

int main()
{
int a[100];
int n, t = 0;
cout << "input the size of array:" << endl;
cin >> n;
for (size_t i = 0; i < n; ++i)
cin >> a[i];
for (size_t i = 0; i < n; ++i)
{
int key = a[i];
int temp = 0;
for (size_t j = i; j < n; ++j)
{
if (a[j] < key)
{
key = a[j];
t = j;
}
}
a[t] = a[i];
a[i] = key;
}
for (size_t i = 0; i < n; ++i)
cout << a[i] << " ";
cout << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: