使用的是选择排序法,先选择最小的数,然后将其放在第一位;然后寻找第二小的数,将其放在第二位;依次类推……
#include<iostream>
using namespace std;
void selectionSort(int arr[], int n)//数组和数组中元素的个数
{
for (int i = 0; i < n; i++){
//寻找[i,n)区间里的最小值
int minIndex = i;
for (int j = i + 1; j < n; j++){
if (arr[j] < arr[minIndex])
minIndex = j;//寻找最小值元素的索引号
}
swap(arr[i], arr[minIndex]);
}
}
int main()
{
int a[10] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
selectionSort(a, 10);
for (int i = 0; i < 10; i++)
{
cout << a[i] << " " ;
}
cout << endl;
system("pause");
return 0;
}