一个整型数组,完成快速排序
思路:选取一个元素作为哨兵元素,遍历数组,比哨兵元素小的元素放在左侧,比哨兵元素大的放在右侧,再把哨兵元素放在中间位置,递归此过程。
C++代码
QuickSort.h文件
#ifndef QuickSort_h
#define QuickSort_h
#include <stdio.h>
#include <iostream>
#endif /* QuickSort_hpp */
/*
arr为待排序数组
low为数组最小的序号,
high为数组最大的序号
*/
void quickSort(int arr[], int low, int high);
QuickSort.cpp文件
#include "QuickSort.h"
int partition(int arr[], int low, int high) {
if (arr == NULL || low >= high) {
return -1;
}
//选取low位置的元素作为哨兵元素
int sentinel = arr[low];
int i = low;
int j = high;
while (i < j) {
//比哨兵元素小的元素放在数组左侧
while (i < j && arr[j] >= sentinel) {
j--;
}
if (i < j) {
arr[i] = arr[j];
}
//比哨兵元素大的元素放在数组右侧
while (i < j && arr[i] <= sentinel) {
i++;
}
if (i < j) {
arr[j] = arr[i];
}
}
//把哨兵元素放在合适的位置
arr[i] = sentinel;
return i;
}
void quickSort(int arr[], int low, int high){
if (arr == NULL || low >= high) {
return;
}
//获取哨兵元素的位置
int index = partition(arr, low, high);
//递归
quickSort(arr, low, index -1);
quickSort(arr, index + 1, high);
}
.main文件
#include <iostream>
#include "QuickSort.h"
int main(int argc, const char * argv[]) {
int arr[] = {1,3,6,4,8,9,2,7,5};
quickSort(arr, 0, 8);
for (int i = 0; i < 9; i++) {
std::cout<<arr[i]<<std::endl;
}
return 0;
}