How to implement the quick sort algorithm using the C language?
Here is an example code implementing the quicksort algorithm in the C language.
#include <stdio.h>
void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
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[] = { 64, 34, 25, 12, 22, 11, 90 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("排序前的数组:\n");
printArray(arr, n);
quickSort(arr, 0, n - 1);
printf("排序后的数组:\n");
printArray(arr, n);
return 0;
}
The quickSort function in this code is used to implement the quicksort algorithm. The partition function is used to select a pivot element and place elements smaller than the pivot to the left, and elements larger than the pivot to the right. The swap function is used to exchange the values of two elements. The printArray function is used to print the elements of an array. In the main function, we define an example array, call the quickSort function to sort it, and then use the printArray function to print the sorted array.