51 lines
1.0 KiB
C++
51 lines
1.0 KiB
C++
#include "sort.h"
|
|
|
|
#include <cstring>
|
|
|
|
void swap(char **a, char **b) {
|
|
char *temp = *a;
|
|
*a = *b;
|
|
*b = temp;
|
|
}
|
|
|
|
int partition(char **arr, const int first, const int last)
|
|
{
|
|
const char *pivot = arr[last];
|
|
|
|
int i = first;
|
|
for (int j = first; j < last; j++) {
|
|
if (strcmp(arr[j], pivot) <= 0) {
|
|
swap(&arr[i], &arr[j]);
|
|
i++;
|
|
}
|
|
}
|
|
swap(&arr[i], &arr[last]);
|
|
return (i);
|
|
}
|
|
|
|
void quick_sort(char **arr, const size_t length) {
|
|
if (length <= 1) {
|
|
return;
|
|
}
|
|
int low = 0, high = length - 1;
|
|
int stack[high - low + 1];
|
|
int top = -1;
|
|
stack[++top] = low;
|
|
stack[++top] = high;
|
|
while (top >= 0) {
|
|
high = stack[top--];
|
|
low = stack[top--];
|
|
const int pivot_pos = partition(arr, low, high);
|
|
|
|
if (pivot_pos - 1 > low) {
|
|
stack[++top] = low;
|
|
stack[++top] = pivot_pos - 1;
|
|
}
|
|
|
|
if (pivot_pos + 1 < high) {
|
|
stack[++top] = pivot_pos + 1;
|
|
stack[++top] = high;
|
|
}
|
|
}
|
|
}
|