C Quick Sort Algorithm Implementation Using Functions
The C programming language does not have built-in support for macros that can perform a quick sort algorithm. However, you can implement a quick sort algorithm using functions instead of macros. Here is an example implementation of quick sort in C:
#include <stdio.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arr[j] <= pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
printArray(arr, n);
quickSort(arr, 0, n - 1);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
This implementation uses the 'partition' function to divide the array into two partitions based on a pivot element. It then recursively sorts the partitions using the 'quickSort' function. Finally, the 'printArray' function is used to print the sorted array.
Note that this implementation is not a macro but a function-based solution for quick sort in C.
原文地址: https://www.cveoy.top/t/topic/NZv 著作权归作者所有。请勿转载和采集!