直接选择排序

选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理如下。首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。

选择排序的主要优点与数据移动有关。如果某个元素位于正确的最终位置上,则它不会被移动。选择排序每次交换一对元素,它们当中至少有一个将被移到其最终位置上,因此对n个元素的表进行排序总共进行至多n-1次交换。在所有的完全依靠交换去移动元素的排序方法中,选择排序属于非常好的一种。

 1 // 参考白话经典算法之直接选择排序的思想
 2 #include <stdio.h>
 3 
 4 void SwapValue(int *OperatorA, int *OperatorB)
 5 {
 6     if ((NULL == OperatorA) || (NULL == OperatorB))
 7     {
 8         printf ("Invalid Parameter(s)!\n");
 9         return;
10     }
11 
12     if ((*OperatorA) != (*OperatorB))
13     {
14         *OperatorA ^= *OperatorB;
15         *OperatorB ^= *OperatorA;
16         *OperatorA ^= *OperatorB;
17     }
18 }
19 
20 void SelectSort(int *a, int N)
21 {
22     if ((NULL == a) || (N <= 0))
23     {
24         printf ("Invalid Parameter(s)!\n");
25         return;
26     }
27 
28     for (int i = 0; i < N; ++i)
29     {
30         int nMin = i;
31 
32         for (int j = i+1; j < N; ++j)
33         {
34             if (a[j] < a[nMin])
35             {
36                 nMin = j;
37             }
38         }
39 
40         if (nMin > i)
41         {
42             SwapValue (&a[i], &a[nMin]);
43         }
44     }
45 }
46 
47 int main(void)
48 {
49     int a1[9] = {9, 8, 7, 6, 5, 4, 3, 2, 1};
50 
51     SelectSort (a1, 9);
52 
53     for (int i = 0; i < 9; ++i)
54     {
55         printf ("%d ", a1[i]);
56     }
57 
58     printf ("\n");
59 
60     return 0;
61 }

原文地址:https://www.cnblogs.com/ldjhust/p/2986166.html