C语言学习: 快速排序(递归方式)

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

 

posted @ 2023-02-02 23:23  泥古拉斯赵四  阅读(2)  评论(0编辑  收藏  举报