Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- #include <math.h>
- #include <time.h>
- #include"merge_net.h"
- int populateArray (int *,int);// takes in the pointer to array, and size
- int printArray(int *,int);//takes in pointer to array and its size and prints the array
- int main()
- {
- int *array,i,size,bool=0,search=0,mid=0,start=0,end=0;
- do{
- printf("enter the size of array: ");
- scanf("%d",&size);
- array=(int *)malloc(sizeof(int)*size);
- // printf("enter array elements: \n");
- // for(i=0;i<size;i++){
- // scanf("%d",(array+i));
- // }
- populateArray(array,size);
- printArray(array,size);
- partition(array,0,(size-1));
- printf("\nthe array after sorting:\t");
- for(i=0;i<size;i++){
- printf("%d ",*(array+i));
- }
- /*now that sorting is done, we can perform binary search*/
- printf("\n\nenter the value to search: ");
- scanf("%d",&search);
- start=0; // there were problems without this initializtion, as it led to start>end,
- //and while loop getting bypassed, binary search fail, and "search item not found" being printed.
- end=size-1;
- mid=size/2;
- while(start<=end){
- if(*(array+mid)<search){
- start=mid+1;
- printf("\nstart, end, mid : %d %d %d \n",start,end,mid);
- }
- else if(*(array+mid)==search){
- printf("\n%d found at array location: %d \n",search,mid);
- break;
- }
- else if(*(array+mid)>search){
- printf("\nstart, end, mid : %d %d %d \n",start,end,mid);
- end=mid-1;
- }
- mid=(start+end)/2;
- }
- if(start>end){
- printf("search item %d not found.\n\n",search);
- }
- printf("to iterate once more, press 1, else 0 : ");
- scanf("%d",&bool);
- }while(bool==1);
- return 0;
- }
- int populateArray(int *array,int size){
- int i;
- srand(time(NULL));
- printf("populating the array....\n");
- for(i=0;i<size;i++) {
- *(array+i)=rand()%1000; // populates the array with pseudo random numbers from 0-999
- }
- }
- int printArray(int *array,int size){
- int i;
- printf("\nthe array is:\t");
- for(i=0;i<size;i++) {
- printf("%d ",*(array+i));
- }
- puts("\n");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement