Skip to content

Instantly share code, notes, and snippets.

@antony-jr
Created March 17, 2019 13:59
Show Gist options
  • Save antony-jr/ad8c711b333863b0ded5aa9404d365bb to your computer and use it in GitHub Desktop.
Save antony-jr/ad8c711b333863b0ded5aa9404d365bb to your computer and use it in GitHub Desktop.
#include <stdio.h>
void isort(int *arr , int n){
int i = 1,
pos = 0,
v = 0;
while(i < n){
v = arr[i];
pos = i;
while(pos > 0 && arr[pos-1] > v){
arr[pos] = arr[pos-1];
--pos;
}
arr[pos] = v;
++i;
}
}
int binary_search(int *arr , int el , int left , int right){
if(left > right)
return -1;
int mid = (left + right)/2;
if(arr[mid] == el){
return mid;
}else if(arr[mid] > el){
return binary_search(arr,el,left , mid-1);
}
return binary_search(arr,el,mid+1,right);
}
void main(){
int a[100];
int i,n = 0;
int pos = 0;
int el = 0;
printf("Enter the upper limit: ");
scanf("%d" , &n);
for(i=0;i<n;++i){
printf("Enter value[%d]: " , i+1);
scanf("%d" , a + i);
}
isort(a , n);
printf("Sorted Array: ");
for(i=0;i<n-1;++i){
printf(" [%d]( %d ) , " , i+1 , a[i]);
}
printf(" [%d]( %d ) .\n\n" , i+1 , a[i]);
printf("Enter element to search: ");
scanf("%d" , &el);
if((pos = binary_search(a , el , 0 , n)) < 0){
printf("Element not found in the array.\n");
return;
}
printf("Element found at position %d.\n" , pos+1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment