提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
一、思路
pivot是最终枢轴(4),partition是临时枢轴,始终指向第一个比pivot大的元素(7),变量i指向比pivot小的元素(1),当a[i]比pivot小时,交换i和partition(临时的枢轴元素),当a[i]比pivot大时,不用管,就是一趟遍历找到找到比pivot小的元素和临时枢轴partition交换;然后最终将临时枢轴partition和最终枢轴pivot交换即可
- 1.定义pivot等于a[high]
- 2.遍历数组,如果a[i]比pivot小,则交换a[i]和partition
- 3.交换partition和high
二、代码
1.引入库
#include <stdio.h>
#include "io_utils.h"
#include <stdlib.h>
#include <time.h>
#define PLAYER_COUNT 50
void SwapElements(int array[], int first, int second) {
int temp = array[first];
array[first] = array[second];
array[second] = temp;
}
void ShuffleArray(int array[], int length) {
srand(time(NULL));
//[0, RAND_MAX]
for (int i = length - 1; i > 0; --i) {
int random_number = rand() % i;
SwapElements(array, i, random_number);
}
}
int Partition(int array[], int low, int high) {
int pivot = array[high];
int partition = low;
for (int i = low; i < high; ++i) {
if (array[i] < pivot) {
SwapElements(array, i, partition++);
}
}
SwapElements(array, partition, high);
return partition;
}
void QuickSort(int array[], int low, int high) {
if (low >= high) return;
int partition = Partition(array, low, high);
QuickSort(array, low, partition - 1);
QuickSort(array, partition + 1, high);
}
int main() {
int players[PLAYER_COUNT];
for (int i = 0; i < 50; ++i) {
players[i] = i;
}
// players : 0, 1, ..., 49
PRINT_INT_ARRAY(players, PLAYER_COUNT);
ShuffleArray(players, PLAYER_COUNT);
PRINT_INT_ARRAY(players, PLAYER_COUNT);
QuickSort(players, 0, PLAYER_COUNT - 1);
PRINT_INT_ARRAY(players, PLAYER_COUNT);
return 0;
}