两种搜索方式不一样,第 0种单向搜索,第1 种双向搜。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXVAL 8
#define STATIC 0
void display();
int a[MAXVAL] = {8,2,1,3,4,5,6,9};
int quick1(int a[], int sta, int end)
{
int i, j;
int tmp = a[sta],temp;
i = sta + 1;
j = end;
do
{
while(i <= j){if(a[i] >= a[sta]) break; i++;}
if(i >= end)
{
temp = a[i - 1];
a[i - 1] = a[sta];
a[sta] = temp;
return i - 2;
}
while(i < j){if(a[j] < a[sta]) break; j--;}
if(i < j)
{
temp = a[j];
a[j] = a[i];
a[i] = temp;
}
if( i == j)
{
temp = a[i-1];
a[i-1] = a[sta];
a[sta] = temp;
return i-1;
}
}while(1);
return -1;//avoid warning,not used.
}
void quicksort1(int a[],int sta,int end)
{
int mid;
int temp;
if(sta >= end)
{
return;
}
if(end - sta == 1)
{
if(a[sta] > a[end])
{
temp = a[sta];
a[sta] = a[end];
a[end] = temp;
}
return ;
}
mid = quick1(a,sta,end);
quicksort1(a,sta,mid);
quicksort1(a,mid+1,end);
}
int quick0(int a[], int sta, int end)
{
int i,j;
int tmp = a[sta],temp;
for(i = j = sta+1; i < end; i++)
{
if(a[i] <= tmp)
{
temp = a[j];
a[j] = a[i];
a[i] = temp;
j++;
}
}
temp = a[j-1];
a[j-1] = a[sta];
a[sta] = temp;
return j-1;
}
void quicksort0(int a[],int sta,int end)
{
int mid;
if(sta >= end)
{
return;
}
display();
mid = quick0(a,sta,end);
quicksort0(a,sta,mid);
quicksort0(a,mid+1,end);
}
void display()
{
int i = 0, j = 0;
for(i = 0; i < MAXVAL; i++)
{
j += printf("%d ",a[i]);
if(j >= 50)
{
j = 0;
printf("\n");
}
}
printf("\n");
}
bool verify(int a[])
{
int i;
for(i = 1; i < MAXVAL; i++)
{
if(a[i-1] > a[i])
return false;
}
return true;
}
int main()
{
int i = 0,j = 100;
srand(time(NULL));
#if STATIC == 0
for(i = 0; i < MAXVAL; i++)
{
a[i] = rand() %20;//random some data
}
#endif
quicksort1(a,0,MAXVAL-1);// or quicksort0(a,0,MAXVAL);
if(!verify(a))
{
printf("error \n");
display();
}
return 0;
}