十大经典排序算法之选择排序

【选择排序】(Select Sort)

a)    原理

选择排序工作原理是查找剩余数组元素中最小(或最大)元素,然后放到数组开始处,进行排序。以此类推,直到所有元素排序完成。

b)    演示动态图

 

c)    算法步骤

l  查找所有元素,找到数组中最小元素,并记住其索引(坐标);

l  将最小元素与第一个元素交换,使得最小元素在最前列;

l  查找剩余元素,寻找最小元素与第二个交换。

l  以此类推。

c)    代码实现

 1 #include <iostream>
 2 
 3 using namespace std;
 4 void SelectSort(int [],int);
 5 void PrintStr(int [],int);
 6 
 7 int main()
 8 {
 9     int str[] = {2,5,6,1,53,26,64,18,98,11};
10     int strlen = sizeof(str)/sizeof(str[0]);
11     cout << "排序前数组序列:";
12     PrintStr(str,strlen);
13     SelectSort(str,strlen);
14     cout << "排序后数组序列:";
15     PrintStr(str,strlen);
16     return 0;
17 }
18 void SelectSort(int str[],int strlen)
19 {
20     int minIndex,temp;
21     for (int i = 0; i < strlen; i++)
22     {
23         minIndex = i;
24         for (int j = i + 1; j < strlen;j++)
25         {
26             if (str[j] < str[minIndex])
27             {
28                 minIndex = j;//找到最小的数的索引
29             }
30         }
31         temp = str[minIndex];
32         str[minIndex] = str[i];
33         str[i] = temp;
34     }
35 }
36 void PrintStr(int str[],int strlen)
37 {
38     for (int i = 0;i < strlen;i++)
39         cout << str[i] << ',';
40     cout << endl;
41 }

参考博客:https://www.cnblogs.com/onepixel/articles/7674659.html,再次感谢!

猜你喜欢

转载自www.cnblogs.com/xdak/p/10994990.html