C++快速排序法代码怎么写
导读:下面是一个示例的C++快速排序算法的代码: #include <iostream> using namespace std; // 交换两个元素的值 void swap(int* a, int* b { int te...
下面是一个示例的C++快速排序算法的代码:
#include iostream>
using namespace std;
// 交换两个元素的值
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
// 将数组划分为两个子数组,小于pivot的放在左边,大于pivot的放在右边
int partition(int arr[], int low, int high) {
int pivot = arr[high];
// 选择最右边的元素作为pivot
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);
// 对右子数组进行快速排序
}
}
// 打印数组
void printArray(int arr[], int size) {
for (int i = 0;
i size;
i++) {
cout arr[i] " ";
}
cout endl;
}
int main() {
int arr[] = {
8, 3, 6, 2, 1, 5, 7, 4 }
;
int size = sizeof(arr) / sizeof(arr[0]);
cout "原数组:";
printArray(arr, size);
quickSort(arr, 0, size - 1);
cout "排序后:";
printArray(arr, size);
return 0;
}
这段代码首先定义了一个用于交换两个元素的函数swap,然后定义了一个用于将数组划分为两个子数组的函数partition,最后定义了一个快速排序函数quickSort。quickSort函数在递归调用中对左右子数组进行快速排序,而partition函数则根据选定的pivot将数组进行划分。
在主函数main中,首先定义了一个待排序的数组arr,然后调用quickSort函数进行快速排序,最后调用printArray函数打印排序后的数组。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: C++快速排序法代码怎么写
本文地址: https://pptw.com/jishu/580079.html
