用C++写快速排序模板
时间: 2023-09-03 14:25:02 浏览: 66
### 回答1:
好的,以下是使用C语言编写的快速排序模板:
```c
#include <stdio.h>
void quicksort(int arr[], int low, int high) {
int i = low, j = high;
int pivot = arr[(low + high) / 2];
while (i <= j) {
while (arr[i] < pivot) {
i++;
}
while (arr[j] > pivot) {
j--;
}
if (i <= j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
if (low < j) {
quicksort(arr, low, j);
}
if (i < high) {
quicksort(arr, i, high);
}
}
int main() {
int arr[] = { 9, 2, 5, 7, 1, 6, 8, 3, 10, 4 };
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]);
}
printf("\n");
return 0;
}
```
以上代码中,使用了快速排序算法来对一个整型数组进行排序。其中,`quicksort` 函数是递归调用的,通过比较数组中的元素与一个主元(即“枢轴元素”或“基准元素”)来实现排序。
### 回答2:
快速排序是一种常用的排序算法,通过递归地将数组分成较小的子数组,然后分别对子数组进行排序,直到整个数组有序。
以下是用C语言写的快速排序模板:
```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 pivotIndex = partition(arr, low, high);
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
printf("原始数组:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
quickSort(arr, 0, n - 1);
printf("\n排序后的数组:");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
这个模板中包含一个`swap`函数,用于交换两个元素的位置。`partition`函数用于选择一个主元(pivot),并按照主元将数组分成两个部分。`quickSort`函数通过递归调用自身,对分割后的子数组进行排序。最后,在`main`函数中,我们定义了一个待排序的数组,并调用`quickSort`函数进行排序。我们可以看到,输出的结果是将数组升序排列。
### 回答3:
快速排序是一种常用的排序算法,它的基本思想是选择一个元素作为基准值,通过一趟排序将待排序序列分割成独立的两部分,其中一部分的所有元素都比基准值小,另一部分的所有元素都比基准值大。然后对这两部分继续进行快速排序,直到整个序列有序。
以下是用C语言实现快速排序的模板:
```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[low];
int i = low, j = high;
while (i < j) {
while (i < j && arr[j] >= pivot)
j--;
if (i < j)
arr[i++] = arr[j];
while (i < j && arr[i] <= pivot)
i++;
if (i < j)
arr[j--] = arr[i];
}
arr[i] = pivot;
return i;
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pivot_pos = partition(arr, low, high);
quickSort(arr, low, pivot_pos - 1);
quickSort(arr, pivot_pos + 1, high);
}
}
int main() {
int arr[] = {5, 2, 8, 3, 1, 9, 4, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("排序后的数组:");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
```
上述代码实现了快速排序的模板,其中swap函数用于交换两个元素的值,partition函数用于通过一趟排序将待排序序列分割成独立的两部分,quickSort函数用于递归调用实现快速排序。
运行程序后,输出结果为:1 2 3 4 5 6 7 8 9,表示数组已经按照从小到大的顺序排列好了。