#include<iostream>
#include<algorithm>//调用算法库,使用交换函数swap
#include<cstdio>
using namespace std;
void quickSort(int *arr, int begin, int end);
int quickPart(int arr[], int low, int high);
void swap(int *arr, int i, int j);
// 冒泡排序
void bubbleSort(int *arr, int n)
{
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j])
swap(arr[i], arr[j]);
}
}
}
void insertSort(int a[], int n)
{
// 选择排序 我们获取当前没有排好序中的最大(小)的元素和数组最右(左)端的元素交换
for (int i = 0; i < n; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
if (a[min] > a[j])
min = j; // 交换下标位置
}
if (i != min) swap(a[i], a[min]);
}
}
// 快速排序:选第一个对象作为基准,按照该对象的排序码大小,将整个对象
// 序列划分为左右两个字序列:
// 左侧子序列中所有对象的排序码都小于或等于基准对象的排序码;
// 右侧子序列中所有对象的排序码都大于基准对象的排序码;
// 基准对象则排在这两个子序列中间,这也是该对象最终应放的位置
// 然后分别对这两个子序列重复施行上述方法,直到所有的对象都排在相应位置上为止
void quickSort(int *arr, int begin, int end)
{
//begin为左,end为右
//如果区间不只一个数
if (begin < end) {
int mid = quickPart(arr, begin, end); // 对序列arr[low]到arr[high]作一趟快速排序
//对基准元素的左边子区间进行相似的快速排序
quickSort(arr, begin, mid - 1);
//对基准元素的右边子区间进行相似的快速排序
quickSort(arr, mid + 1, end);
}
return;
}
// 一次快速排序算法
int quickPart(int arr[], int low, int high) {
int i = low;
int j = high;
int temp = arr[low]; // 取第一个作为基准
while (i < j) {
while ((i < j) && arr[j] >= temp) // 从右向左扫描
j--;
//将右边小于等于基准元素的数填入右边相应位置
arr[i] = arr[j];
while ((i < j) && arr[i] < temp) // 从左向右扫描
i++;
//将左边大于基准元素的数填入左边相应位置
arr[j] = arr[i];
}
//将基准元素填入相应位置
arr[i] = temp;
return i;
}
int main()
{
int a[11] = { -5, 4, 3, 2, 1, 10, 9, 8, 7, 6, 11 };
//int a[] = {23, 45, 17, 11, 13, 89, 72, 26, 3, 17, 11, 13};
int n = sizeof(a) / sizeof(a[0]);
// bubbleSort(a, n - 1);
// insertSort(a, n - 1);
quickSort(a, 0, n - 1);
for (int i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
return 0;
}