#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef int ElemType;
typedef struct {
ElemType *ele;
int length;
} Table;
void initTable(Table &table, int length) {
table.ele = (ElemType *) malloc(sizeof(ElemType) * length);
table.length = length;
srand(time(NULL));
for (int i = 0; i < table.length; i++) {
table.ele[i] = rand() % 100;
}
}
void printTable(Table table) {
for (int i = 0; i < table.length; i++) {
printf("%3d", table.ele[i]);
}
}
void swap(int &a, int &b) {
int temp;
temp = a;
a = b;
b = temp;
}
//让小的数值在分割点左边,大的在右边
int partition(ElemType *el, int low, int heigh) {
int pivot = el[low];
while (low < heigh) {
while (low < heigh && el[heigh] >= pivot) {
heigh--;
}
//不符合循环条件时
el[low] = el[heigh];
while (low < heigh && el[low] <= pivot) {
low++;
}
//不符合循环条件时
el[heigh] = el[low];
}
el[low] = pivot;
return low;
}
void quickSort(ElemType *el, int low, int heigh) {
if (low < heigh) {
int pivot = partition(el, low, heigh);
quickSort(el, low, pivot - 1);//前一半排序
quickSort(el, pivot + 1, heigh);//后一半排序
}
};
int main() {
Table table;
initTable(table, 10);
printTable(table);
printf("\n");
quickSort(table.ele, 0, 9);
printTable(table);
return 0;
}
16.5快速排序
于 2024-01-20 13:44:40 首次发布