快速排序
#include<iostream>
using namespace std;
void swap(int arr[], int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
void QuickSort(int arr[], int left, int right)
{
//取一个数为基准,大于这个基准的放在右边,小于这个数的放在左边
if(left < right)
{
int temp = arr[left];//基准取最左边的数
int i = left;
int j = right;
while(i < j)
{
while(i < j && arr[j] >= temp)
j--;
if(i<j)
swap(arr,i,j);
while(i < j && arr[i] <= temp)
i++;
if(i < j)
swap(arr,i,j);
}
arr[i] = temp;
QuickSort( arr,left, i -1);
QuickSort(arr, i + 1, right);
}
}
int main()
{
int arr[] = {34, 65, 12, 43, 67, 5, 78, 10, 3, 70};
int len = sizeof(arr)/ sizeof(int);
cout << "The original array are: " <<endl;
for(int i = 0; i < len; i++)
cout << arr[i] << ",";
cout << endl;
QuickSort(arr, 0, len - 1);
cout <<"The sorted arr are: " << endl;
for(int j = 0; j < len; j++)
cout << arr[j] << ",";
cout << endl;
system("pause");
return 0;
}
快速排序是运用递归的思想, 选择一个中间值,然后把数组中大于这个中间值得放在右边,小于的放在左边,然后递归排序左边和右边地数组,知道左边和右边地数组个数为1