C++ 快速排序的实现 左右同时开弓
废话少说,直接上代码.
#include <iostream>
#include <math.h>
using namespace std;
void swap(int * v, int left, int right);
bool check_pos(int *v, int pos, int len);
void quick_sort(int * arr, const int left,const int right);
void swap(int * v, int left, int right)
{
int tmp = v[left];
v[left] = v[right];
v[right] = tmp;
}
bool check_pos(int *v, int pos, int len)
{
bool var = true;
for (int i = 0; i <= len; i++)
{
if((i < pos) && (v[i] > v[pos]))
var =false;
if((i > pos) && (v[i] < v[pos]))
var =false;
}
return var;
}
void quick_sort(int * arr, const int left,const int right)
{
if(right < 0 || left <0)
return;
int pos = left;
while (!check_pos(arr, pos, right))
{
for (int j = right; j > left; j--)
{
if (arr[j] < arr[pos])
{
swap(arr, pos, j);
pos = j;
break;
}
}
for (int k = left; k < right; k++)
{
if (arr[k] > arr[pos])
{
swap(arr, pos, k);
pos = k;
break;
}
}
}
if (right > left)
{
quick_sort(arr, left, pos - 1);
quick_sort(arr, pos + 1, right);
}
else
{
return;
}
}
int main(void)
{
int *arr = new int[10];
for (int i = 0; i < 10; i++)
{
arr[i] = rand();
cout<<arr[i]<<endl;
}
cout<<"**********************************"<<endl;
quick_sort(arr, 0, 9);
for (int i = 0; i < 10; i++)
{
cout<<arr[i]<<endl;
}
delete [] arr;
system("pause");
return 0;
}
注意一点就是:
任意时刻,pos右边的肯定大于它,左边的肯定小于它.