#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <time.h>
int ThreeDivideSearch(int x,int Array[],int low,int high);
void Sort(int Array[],int size);
int Search(int data_to_find,int Array[],int size);
int main(void)
{
int size;
int i;
int data_to_find;
int isFound;
time_t t;
int *Array;
printf("Please input the size of the array:");
scanf("%d",&size);
Array = (int *)malloc(size*sizeof(int));
if( !Array)
{
printf("Out of memory!\n");
exit(1);
}
srand((unsigned) time(&t));
for(i = 0;i < size;i++)
Array[i]=rand()%100;
printf("Random array is :\n");
for(i = 0;i < size;i++)
printf("%d ",Array[i]);
printf("\n");
printf("Sorted array is :\n");
Sort(Array,size);
for(i = 0;i < size;i++)
printf("%d(%d) ",Array[i],i);
printf("\n");
data_to_find = rand()%100;
printf("The data to searh is: %d\n",data_to_find);
isFound = Search(data_to_find,Array,size);
if(isFound == -1)
{
printf("Data is not found!\n");
}
else
{
printf("Data is first found in position %d!\n",isFound);
}
free(Array);
return 0;
}
int Search(int data_to_find,int Array[],int size)
{
return ThreeDivideSearch(data_to_find,Array,0,size - 1);
}
int ThreeDivideSearch(int data_to_search,int Array[],int low,int high)
{
int mid1,mid2;
while(low <= high)
{
printf("low = %d high = %d\n",low,high);
mid1 = low + (high - low) / 3;
if(Array[mid1] == data_to_search)
{
return mid1;
}
mid2 = low + (high - low) * 2 / 3;
if(Array[mid2]= = data_to_search)
{
return mid2;
}
if(Array[mid1] > data_to_search)
{
high = mid1 - 1;
}
else if(Array[mid2] < data_to_search)
{
low = mid2 + 1;
}
else
{
high = mid2 - 1;
low = mid1 + 1;
}
}
return -1;
}
void Sort(int Array[],int size)
{
int i,j,t;
for(i = 0;i < size - 1;i++)
for(j = 0;j < size - i - 1;j++)
if(Array[j] > Array[j+1])
{
t = Array[j];
Array[j] = Array[j+1];
Array[j + 1] = t;
}
}
|