Binary search

i wan to search the array using binary sort, but i had the bubble sort to sort out the array before searching, but what i really want is to display the searched array being in the original position, not position after sorting

can someone help fix it? thanks


#include <stdio.h>
#include<stdlib.h>

void bubblesort(int data[])
{ int pass,j,hold;
for(pass=1; pass<=4; pass++)
{ for (j=0; j<=3; j++)
if(data[j]>data[j+1])
{ hold=data[j];
data[j]=data[j+1];
data[j+1]=hold;
}
}
}

void binarySearch(int data[])
{ int middle, n;

int start = 0;
int end = 9;
middle = (start+end)/2;

printf("Integer to search: ");
scanf("%d",&n);

while(start <= end)
{
if ( data[middle] < n )
start = middle + 1;
else if ( data[middle] == n )
{ printf("\n\t\tIndex\tData");
printf("\n\t\t%d\t%d\n", middle+1, n);
break;
}
else
end = middle - 1;
middle = (start+end)/2;
}
if ( start > end )
printf("Not found! %d is not in data\n", n);
}

void main()
{ int data[10]={19,16,23,35,49,4,13,10,3};

bubblesort(data);
binarySearch(data);
}
Last edited on
Binary search can not work on an unsorted array.
@ResidentBiscuit
i wasnt able to find 45 in the search;

#include <stdio.h>
#include<stdlib.h>

void bubblesort(int data[])
{ int i, j, temp;
for(i=1; i<10; i++)
{ for(j=0;j< 9;j++)
{ if(data[j]>data[j+1])
{ temp=data[j];
data[j]=data[j+1];
data[j+1]=temp;
}
}
}
int l;
for(l=0; l<=4; l++)
{ if(l%20==0)
printf("\nAfter pass: ");
printf("%2d\t", data[l]);
}

}


void main()
{ int data[10]={19,16,23,35,49,4,13,10,3};

bubblesort(data);
printf("After sort:");

}
Fix this ordination method, and should be 10 numbers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void bubblesort(int data[])
{ 
     int hold;
     for( int i=0; i < 10 ; i++)
     { 
         for (int j= i+1; j<10 ; j++)
             if( data[i] > data[j] )
             { 
                hold = data[i];
                data[i] = data[j];
                data[j] = hold;
             }
     }
}


You need a (1) number to put in the array.
 
int data[10]={19,16,23,35,49,4,13,10,3,    2      };


Try to see what happens..
Last edited on
got it fixed it, thx
Topic archived. No new replies allowed.