分治法快速排序写法C语言?
时间: 2024-11-22 22:45:14 浏览: 25
分治法是一种常用的算法设计策略,其中快速排序是一种经典的基于分治思想的排序算法。在C语言中,快速排序的基本步骤如下:
```c
#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); // Index of smaller element
for (int j = low; j <= high - 1; j++) {
if (arr[j] < pivot) {
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]); // put pivot in right place
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); // recursively sort elements before pivot
quickSort(arr, pi + 1, high); // recursively sort elements after pivot
}
}
// 主函数演示
int main() {
int data[] = {9, 7, 5, 11, 12, 2, 14, 3, 10};
int n = sizeof(data) / sizeof(data[0]);
quickSort(data, 0, n - 1);
printf("Sorted array: \n");
for (int i=0; i < n; i++)
printf("%d ", data[i]);
return 0;
}
```
这个程序首先选择一个基准值,然后将小于它的数移动到左边,大于它的数移动到右边,接着递归地对左右两边进行同样的操作,直到整个序列有序。
阅读全文
相关推荐


















