modify other_binary_search

This commit is contained in:
koseokkyu 2017-11-20 16:08:47 +09:00
parent 04527dfc56
commit c3bd560d4c

View File

@ -2,49 +2,49 @@
#include <stdlib.h> #include <stdlib.h>
#define len 5 #define len 5
int binarySearch(int array[] , int len , int searchX)
int binarySearch(int array[], int leng, int searchX)
{ {
int pos = -1, right, left, i = 0;
int pos = -1 , right , left , i = 0; left = 0;
right = leng - 1;
left = 0; for (i = 0; i < leng; i++)
right = len - 1; {
pos = (left + right) / 2;
for(i = 0; i < len ; i++) if (array[pos] == searchX)
{ return pos;
pos = (left + right)/2; else
{
if(array[pos] == searchX) if (array[pos] < searchX)
return pos; left = pos + 1;
else else
{ {
if(array[pos] < searchX) right = pos - 1;
right = pos - 1; }
else }
{ }
left = pos + 1 ;
}
}
}
} }
void main(int argc , char *argv[]) void main(int argc, char *argv[])
{ {
int array[len] = { 5, 8 , 10 , 14 ,16}; int array[len] = { 5, 8 , 10 , 14 ,16 };
int position; int position;
position = binarySearch(array , len , 5); position = binarySearch(array, len, 5);
if( position < 0) if (position < 0)
printf("The number %d doesnt exist in array\n",5); printf("The number %d doesnt exist in array\n", 5);
else else
{ {
printf("The number %d exist in array at position : %d \n",5,position); printf("The number %d exist in array at position : %d \n", 5, position);
} }
} }