您的位置:首页 > 理论基础 > 数据结构算法

经典算法与数据结构的c++实现——直接选择排序

2016-03-19 08:47 716 查看
因为是经典的算法,所以网上描述一大把,直接上个图,直观些,给记性不好的菜鸟(如我)一点儿提示。



算法很简单,遍历整个数组,依次选取最小值放到数组前面。

下面是代码(欢迎批评指点,之后应该会放到github上:https://github.com/y277an/princeton_algs4):

//---------------------------------Specification of Program------------------------------
// Program Name:直接选择排序
// Tools:VS_2013
// Language: C++
// Description: 可自由输入,不需要提早知道数据长度
// Date:2016.3.18
// Author:mseddl
//----------------------------------------------------------------------------------------

#include <iostream>
using namespace std;
void Swap(int& one, int & another)
{
one ^= another;
another ^= one;
one ^= another;
}
void SelectSort(int *arr, int len)
{
for (int i = 0; i < len-1; i++)
{
int nSmallest = arr[i];
int flag(i);//记录新产生的最小值的索引
for (int j = i; j < len; j++)
{
if (arr[j] < nSmallest)
{
nSmallest = arr[j];
flag = j;
}
}
if (flag != i)
{
Swap(arr[i], arr[flag]);
}

}
}
int main()
{
int len(0), temp;
int *arr = new int[100];
char ch;
cout << "请输入要排序的数字,以空格隔开:";
while (1)
{
cin >> temp;
arr[len++] = temp;
cin.get(ch);
if (ch == '\n')
{
break;
}
}
SelectSort(arr, len);
cout << "排序后的数字为:";
for (int i = 0; i < len; i++)
{
cout << arr[i] << " ";
}
cout << endl;
delete[] arr;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: