Sunday, August 19, 2012

Binary Search & Bubble Sort Using C

Language: C
Compiler: Turbo C

#include<stdio.h>
#include<conio.h>


void main(){
clrscr();
int array[] = {12,3,4,67,89,2,4,67,7,8}, num=0, upper =0, lower=0, limit = 10, search = 0;
printf("Enter the number to search:");
scanf("%d",&num);

//sorting
int i=0, j =0, sort = 0, swap=0;
for(i=0;i<9;i++){
    sort=1;
    for(j=1;j<10;j++){
        if(array[j]<array[j-1]){
        swap = array[j];
        array[j]=array[j-1];
        array[j-1]=swap;
        sort=0;
        }
    }
    if(sort==1){
    break;
    }

} //end of sorting
//for(i=0;i<10;i++){
//    printf("%d ",array[i]);

//}
//getch();
//algorithm for binary search
upper = limit-1;
lower=0;
while(upper>=lower){
    if(array[(upper+lower)/2]==num){
        printf("Your search is successful.");
        search =1;
        break;
    }
    else if(array[(upper+lower)/2]>num){
        upper = (upper+lower)/2-1;
           //lower = 0;
    }
    else if(array[(upper+lower)/2]<num){
        lower=(upper+lower)/2+1;
    }
}
if(search ==0){
printf("Number not found.");
}
getch();
}//end of main


PS: Many improvements are possible in the program. You are welcome to suggest them in comments! :)

No comments:

Post a Comment