C Macro-Based Quick Sort for 3-Vectors
Here's a quick macro sort implementation in C for a three-vector:
#include <stdio.h>
#define SWAP(x, y) do { typeof(x) temp = x; x = y; y = temp; } while (0)
void quickSort(int arr[][3], int left, int right) {
int i, j, pivot;
if (left < right) {
pivot = left;
i = left;
j = right;
while (i < j) {
while (arr[i][0] <= arr[pivot][0] && i < right)
i++;
while (arr[j][0] > arr[pivot][0])
j--;
if (i < j) {
SWAP(arr[i][0], arr[j][0]);
SWAP(arr[i][1], arr[j][1]);
SWAP(arr[i][2], arr[j][2]);
}
}
SWAP(arr[pivot][0], arr[j][0]);
SWAP(arr[pivot][1], arr[j][1]);
SWAP(arr[pivot][2], arr[j][2]);
quickSort(arr, left, j - 1);
quickSort(arr, j + 1, right);
}
}
int main() {
int arr[][3] = {{3, 2, 1}, {1, 3, 2}, {2, 1, 3}, {1, 2, 3}, {3, 1, 2}};
int n = sizeof(arr) / sizeof(arr[0]);
int i;
printf("Before sorting:\n");
for (i = 0; i < n; i++) {
printf("%d %d %d\n", arr[i][0], arr[i][1], arr[i][2]);
}
quickSort(arr, 0, n - 1);
printf("\nAfter sorting:\n");
for (i = 0; i < n; i++) {
printf("%d %d %d\n", arr[i][0], arr[i][1], arr[i][2]);
}
return 0;
}
Explanation:
- The
quickSortfunction takes an arrayarr, left indexleft, and right indexrightas parameters. - It selects a pivot element from the array (in this case, the element at index
left), and partitions the array such that all elements smaller than the pivot are on its left, and all elements greater than the pivot are on its right. - It then recursively applies the same process to the left and right partitions until the array is sorted.
- The
SWAPmacro is used to swap elements in the array. - In the
mainfunction, a sample arrayarris defined and its sizenis calculated. - The array is printed before sorting.
- The
quickSortfunction is called with the array, left index 0, and right indexn-1. - Finally, the sorted array is printed.
原文地址: https://www.cveoy.top/t/topic/NZH 著作权归作者所有。请勿转载和采集!