#include <iostream>
using namespace std;
// 选择排序
void selectSort(int* arr, int len);
int main(void)
{
int arr[] = { 2, 6, 90, 74, 65, 87, 150, 653, 42, 78, 189, 68, 35, 701, 123, 59, 456 };
int len = sizeof(arr) / sizeof(arr[0]);
cout << "排序前:" << endl;
for (size_t i = 0; i < len; i++)
{
cout << arr[i] << " ";
}
cout << endl;
selectSort(arr, len);
cout << "排序后:" << endl;
for (size_t i = 0; i < len; i++)
{
cout << arr[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
void selectSort(int* arr, int len)
{
int temp = 0;
size_t sub = 0;
for (int i = 0; i < len - 1; i++)
{
temp = arr[i];
sub = i;
for (int j = i + 1; j < len; j++)
{
if (temp > arr[j]) // 找最小数
{
temp = arr[j]; // 重新设定最小数
sub = j; // 记录位置
}
}
if (i != sub) // 调换位置
{
arr[i] = arr[i] + arr[sub];
arr[sub] = arr[i] - arr[sub];
arr[i] = arr[i] - arr[sub];
}
}
}
选择排序算法
最新推荐文章于 2023-03-20 01:02:49 发布