C语言学习: 案例: 指针版本的快速排序

 

 

 

 

 

 

 

 

 1 #include <stdio.h>
 2 #include "io_utils.h"
 3 #include <stdlib.h>
 4 #include <time.h>
 5 
 6 void SwapInt(int *a, int *b) {
 7   int temp = *a;
 8   *a = *b;
 9   *b = temp;
10 }
11 
12 void Shuffle(int *array, int length) {
13   srand(time(NULL));
14 
15   for (int i = length - 1; i > 0; --i) {
16     int random_number = rand() % i;
17     SwapInt(array + i, array + random_number);
18   }
19 }
20 
21 int *Partition(int *low, int *high) {
22   int pivot = *(low + (high - low) / 2);
23   int *p = low;
24   int *q = high;
25 
26   while (1) {
27     while (*p < pivot) p++;
28     while (*q > pivot) q--;
29 
30     if (p >= q) break;
31     SwapInt(p, q);
32   }
33 
34   return q;
35 }
36 
37 void QuickSort(int *low, int *high) {
38   if (low >= high) return;
39   int *partition = Partition(low, high);
40   QuickSort(low, partition - 1);
41   QuickSort(partition + 1, high);
42 }
43 
44 #define PLAYER_COUNT 10
45 
46 int main() {
47   int *players = malloc(sizeof(int) * PLAYER_COUNT);
48   if (!players) {
49     return 1;
50   }
51   for (int i = 0; i < PLAYER_COUNT; ++i) {
52     players[i] = i;
53   }
54   Shuffle(players, PLAYER_COUNT);
55   PRINT_INT_ARRAY(players, PLAYER_COUNT);
56   QuickSort(players, players + PLAYER_COUNT - 1);
57   PRINT_INT_ARRAY(players, PLAYER_COUNT);
58   free(players);
59 
60   return 0;
61 }

 

posted @ 2023-02-04 17:09  泥古拉斯赵四  阅读(4)  评论(1编辑  收藏  举报