选择排序和冒泡排序不管是在算法的思路上还是代码的实现上都差别不大。不同在于,选择排序可以算作是冒泡排序的一种改进,这种改进主要体现在数据的移动次数上面。冒泡排序每次比较后,如果后面的元素有和比当前的元素大或者小,就会交换位置。而选择排序,比较后是记录当前的最小值得位置,一趟比较完成后才做交换。这样的话,就减少了交换的次数。
选择排序的代码实现如下:
#include "stdafx.h"
#include <iostream>
using namespace std;
void print(int data[], int n)
{
for (int i = 0; i < n; i++)
{
cout << data[i] << " ";
}
cout << endl;
}
void select_ascending_sort(int data[], int len)
{
int i = 0, j = 0, temp = 0, x = 0;
for (i = 0; i < len; i++)
{
temp = data[i];//temporarily store this value
for (j = i + 1; j < len; j++)
{
if (temp > data[j])
{
temp = data[j];//save this sort fo minimum
x = j;//save this sort of mininum number
}
}
data[x] = data[i];
data[i] = temp;
}
}
void select_desending_sort(int data[], int len)
{
int i = 0, j = 0, temp = 0, d = 0;
for (i = 0; i < len; i++)
{
temp = data[i];
for (j = i+1; j < len; j++)
{
if (temp < data[j])
{
temp = data[j];
d = j;
}
}
data[d] = data[i];
data[i] = temp;
}
}
int main()
{
int num[] = {5,3, 7,4,3,9,6,2,10,4,3,7,1};
int len = sizeof(num) / sizeof(int);
cout << "data count:"<< len << ". before sort: ";
print(num, len);
select_ascending_sort(num, len);
cout << "after ascending sort: ";
print(num, len);
select_desending_sort(num, len);
cout << "after desending sort: ";
print(num, len);
return 0;
}
来源:CSDN
作者:酸菜鱼的鱼
链接:https://blog.csdn.net/u010299133/article/details/104165826