快速排序算法是一种高效的排序算法,其核心思想是分治法,快速排序算法通过对数组进行划分,将较小和较大的元素分别放在左边和右边,然后递归地对左右两个子数组进行排序,最终得到一个有序的数组。
在C语言中,我们可以使用以下代码实现快速排序算法:
```c
#include
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
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);
int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
return 0;
```
在上面的代码中,我们首先定义了一个 `swap()` 函数来交换两个元素的值,然后我们定义了一个 `partition()` 函数,该函数用于将数组划分为两个子数组,并返回划分点的索引,在 `quickSort()` 函数中,我们首先检查 `low` 是否小于 `high`,如果是,则调用 `partition()` 函数获取划分点,然后递归地对左右两个子数组进行排序,在 `main()` 函数中,我们定义了一个整数数组,并调用 `quickSort()` 函数对其进行排序,排序后,我们使用 `printf()` 函数输出有序的数组。
快速排序算法的时间复杂度为 O(nlogn),其中 n 是数组的大小,快速排序算法具有较高的效率和稳定性,适用于大规模数据的排序。