#include "test.h"
int main()
{
//test(1);
int x, location = 0;
test(2);
printf("input the number to serch: \n");
scanf("%d", &x);
if((location = binarySearch(number,x,MAX)) != 0)
printf(" location is %d \n", location);
else
printf(" location is invalid \n");
//test(3);
getchar();
getchar();
}
void test(int type){
int i = 0, num = 0;
srand(time(NULL));
counter = 0;
printf("before: \n");
for(i = 0; i< MAX; i++)
{
number[i] = rand() % MAX;
printf(" %d ", number[i]);
}
printf("\n\n");
switch(type){
case 1:
quicksort(number, 0, MAX-1);
printf(" quicksort: %d ;\n", counter++);
break;
case 2:
quicksort_m(number, 0, MAX-1);
printf(" quicksort_m: %d ;\n", counter++);
break;
case 3:
quicksort_o(number, 0, MAX-1);
printf("quicksort_o : %d ;\n", counter++);
break;
default:
break;
}
for(i = 0; i< MAX; i++)
printf(" %d", number[i]);
printf("\n");
}
void quicksort(int number[], int left, int right)
{
int i, j, s;
if(left < right){
i = left;
j = right+1;
s = number[left];
while(1){
while( i+1 < MAX && number[++i] < s);
while( j -1 > -1 && number[--j] > s);
if( i >= j)
break;
SWAP(number[i], number[j]);
}
number[left] = number[j];
number[j] = s;
counter++;
quicksort(number, left, j-1);
quicksort(number, j+1, right);
}
}
void quicksort_m(int number[], int left, int right)
{
int i, j, s;
if(left < right){
i = left-1;
j = right+1;
SWAP(number[left], number[(left+right)/2]);
s = number[left];
while(1){
while( number[++i] < s);
while( number[--j] > s);
if( i >= j)
break;
SWAP(number[i], number[j]);
}
counter++;
number[left] = number[j];
number[j] = s;
quicksort_m(number, left, j-1);
quicksort_m(number, j+1, right);
}
}
void quicksort_o(int number[], int left, int right)
{
int num = 0;
if(left < right){
num = partition(number, left, right);
quicksort_o(number, left, num-1);
quicksort_o(number, num+1, right);
}
}
int partition(int number[], int left, int right){
int i = left - 1;
int j = 0;
int x = number[right];
for( j = left; j < right; j++){
if(number[j] < x){
i++;
SWAP(number[i], number[j]);
}
}
SWAP(number[i+1],number[right]);
counter++;
return i+1;
}
void test_middle(int count){
int a = 0, b = 0, mid = 0, i = 0;
srand(time(NULL));
while(i++ < 10){
a = rand() %100;
b = rand() % 100;
mid = (a + b)/2;
printf("a = %d, b = %d, mid = %d \n" , a, b, mid);
}
}
int binarySearch(int a[], int x, int n){
int left = 0;
int right = n-1;
int middle;
while(left <= right){
middle = (left + right)/2;
//printf("x = %d, left = %d, right = %d, mid = %d\n", x, left, right, middle);
if( x < a[middle])
right = middle -1;
else if(x > a[middle])
left = middle + 1;
else
return middle;
}
return 0;
}