Binary Search

Posted by Bl4ckB0y On 17.17 0 comments

Binary Search
#include "stdio.h"
#include "conio.h"
#include "string.h"
#include "stdlib.h"
/*this is funtion binary search, this funtion search a element
using the middle element as pivot and the element divided into 2 sub element
left elements are the element which less than pivot
right elements are the element which more than pivot
so the array must be sort before to use this function
if the search element more than pivot,
it will divide the right element and take the middle element of
right element as pivot, so will left element*/
void search(int array[20],int value,int cari,int pivot)
{
if(cari > array[pivot] && array [pivot] != '\0' && pivot>=0 && pivot<=value)/*it
define the right element*/
{
pivot=(value-pivot)/2+pivot;
search(array,value,cari,pivot);
}
else
if(array[pivot]>cari && array[pivot] !='\0' && pivot>=0 && value>=pivot) /*it define
the left element*/
{
value=pivot;
pivot=value/2;
search(array,value,cari,pivot);
}
else
if (cari == array[pivot]) /*it the pivot, program stop until the subject same with pivot
or not found int anoather*/
{printf(" \n found in index %d ",pivot+1);}
else
{printf("\n NOT FOUND!!!");}
}
/*this function to swap array*/
void swap(int array[20], int i, int p)
{
int g;
g=array[i];
array[i]=array[p];
array[p]=g;
}
/*this funtion to print array after the element sorted*/
void print(int array[20], int n)
{
for (int i=0;n>i;i++)
{
printf("%3d ",array[i]);
}
}
/*this function is selection sort you can use another sorting like buble sort*/
void selection(int array[20], int n)
{
int p;
for(int i=0;n-1>=i;i++)
{
p=i;
for(int j=1+i;n>j;j++)
{
if(array[p]>array[j])
{p=j;}
swap(array,i,p); /*to swap element of array*/
}
}
print(array,n);
}
/*this funtion to get input array from user*/
int input(int array[20])
{
int k;
printf("how much the array : ");
scanf("%d",&k);
for (int i=0;k>i;i++)
{
printf("insert array [%d] : ",i);
scanf("%d",&array[i]);
}
selection(array,k);
return(k);
}
/*this is the m,ain program*/
main(void)
{
printf("Binary Search Program\n");
int array[20],value,cari,pivot;
/*value is long of array*/
/*cari is the element want to search*/
/*i is pivot element*/
value=input(array);
pivot=value/2;
printf("\n\nplease, your choose : ");
scanf("%d",&cari);
search(array,value,cari,pivot);
fflush(stdin);
getch();
getch();
}

Categories:

0 Response for the "Binary Search"

Posting Komentar

your Ads Here

Your Ad Here FellowEquality.com