c++-排序算法-选择排序

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 //选择排序
 6 void selectSort(int arr[], int length)
 7 {
 8     for (int i = 0; i < length - 2; i++)
 9     {
10         int minIndex = i; //用于记录最小元素的索引
11         //找到最小的元素所在的索引
12         for (int j = i + 1; j < length - 1; j++)
13         {
14             if (arr[j] < arr[minIndex])
15                 minIndex = j;
16         }
17         //如果最小元素索引与i不一样,则进行交换
18         if (minIndex != i)
19         {
20             int temp = arr[i];
21             arr[i] = arr[minIndex];
22             arr[minIndex] = temp;
23         }
24     }
25 }
26 
27 //数组打印函数
28 void printArray(int arr[], int length)
29 {
30     for (int i = 0; i < length; i++)
31     {
32         cout << arr[i] << " ";
33     }
34     cout << endl;
35 }
36 
37 int main()
38 {
39     int arr[] = { 5,3,7,1,4,9 };
40     cout << "排序前: " << endl;
41     printArray(arr, 6);
42 
43     selectSort(arr, 6);
44 
45     cout << "排序后: " << endl;
46     printArray(arr, 6);
47     system("pause");
48     return 0;
49 }

 

posted on 2021-10-02 20:05  imbaby  阅读(123)  评论(0)    收藏  举报