数据结构(10) - 顺序排序

顺序排序思想:从左到右依次排序数组,依次拿当前元素和其后的所有元素作比较,根据设定做升序或降序排序。

 1 /**
 2  * C data structure sequence sort example.
 3  * 
 4  * License - MIT.
 5 */
 6 
 7 #include <stdio.h>
 8 #include <string.h>
 9 
10 
11 #define DISPLAY_ARRAY(i, buf, len) \
12         do { \
13             for (i = 0; i < len; i++) \
14                 printf("%d ", buf[i]); \
15             printf("\n"); \
16         } while(0)
17 
18 
19 /**
20  * sequence_sort - Sequence sort.
21 */
22 int sequence_sort(int *buf, int len)
23 {
24     int i = -1,
25         j = -1,
26         tmp = -1;
27 
28     for (i = 0; i < len; i++) {
29         tmp = buf[i];
30 
31         for (j = i - 1; j > -1; j--) {
32             if (tmp >= buf[j])
33                 break;
34             else
35                 buf[j + 1] = buf[j];
36         }
37 
38         buf[j + 1] = tmp;
39     }
40 
41     return 0;
42 }
43 
44 
45 /**
46  * Main function.
47 */
48 int main(void)
49 {
50     int i = 0;
51     int buf[] = {11, 13, 65, 85, 59, 27, 54, 98, 51, 75};
52     int len = sizeof(buf) / sizeof(int);
53 
54     printf("The original array:\n");
55     DISPLAY_ARRAY(i, buf, len);
56 
57     sequence_sort(buf, len);
58 
59     printf("The sort array:\n");
60     DISPLAY_ARRAY(i, buf, len);
61 
62     return 0;
63 }

 

详细请参考Github: [Link] [https://github.com/Phoebus-Ma/C-Helper/tree/main/Class-1/Sort.C].

posted @ 2022-06-25 17:29  this毛豆  阅读(71)  评论(0编辑  收藏  举报