# int数组快速排序

#include <iostream>
#include <stdlib.h>

using namespace std;

class Solution {
public:
int my_qsort(int A[], int n, int i, int k) {
int j;
while (i<k){
if ((j = partition(A,i,k))<0)
return -1;

if (my_qsort(A,n,i,j)<0)
return -1;

i = j+1;// Iterate and sort the right partition
}
}
int partition(int A[], int i, int k){
int r[3],mid;
r[0]=rand()%(k-i+1)+i;
r[1]=rand()%(k-i+1)+i;
r[2]=rand()%(k-i+1)+i;
insert_sort(r,3);
mid = A[ r[1] ];

i--;k++;
while(1){
do{	k--	;}while(compare(A[k],mid)>0);

do{	i++	;}while(compare(A[i],mid)<0);

if(i>=k){
break;
}else{
int tmp;
tmp = A[k];
A[k] = A[i];
A[i] = tmp;
}
}
return k;
}
void insert_sort(int r[], int size){
if (size<=1)
return;
int i, j, pre=0;
for (j=1;j<size;j++){
i=j-1;
int key = r[j];
while(i>=0 && compare(r[i],key)>0){
r[i+1] = r[i];
i--;
}//then the key pos is found
r[i+1] = key;
}
}
int compare(int a1, int key){
if (a1<key)
return -1;// key pos is found
else if(a1>key)
return 1;
else
return 0;
}
};

int main()
{
Solution mySolution;
int A[]={1,6,3,5,7,2,0,4},array_size = 8;
mySolution.my_qsort(A,array_size,0,array_size-1);

int i;
for (i=0;i<array_size;i++)
cout<<A[i]<<' ';

cout <<endl;
system("pause");
return 0;
}

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客