76 lines
1.4 KiB
C
76 lines
1.4 KiB
C
|
#include <stdio.h>
|
||
|
|
||
|
int main()
|
||
|
{
|
||
|
int a,c,n,i,temp;
|
||
|
int flag=0;
|
||
|
int arr[10];
|
||
|
|
||
|
printf("Enter the number of elements you want in the array: ");
|
||
|
scanf("%d",&n);
|
||
|
|
||
|
printf("Enter the numbers you want in the array:\n");
|
||
|
for(i=0;i<n;i++){
|
||
|
scanf("%d",&arr[i]);
|
||
|
}
|
||
|
|
||
|
printf("The numbers in the array are:\n");
|
||
|
for(i=0;i<n;i++){
|
||
|
printf("%d\n",arr[i]);
|
||
|
}
|
||
|
|
||
|
//sorting
|
||
|
int j;
|
||
|
for(i=0;i<n;i++)
|
||
|
{
|
||
|
for(j=0;j<n;j++)
|
||
|
{
|
||
|
if(arr[i]<arr[j])
|
||
|
{
|
||
|
temp = arr[i];
|
||
|
arr[i]=arr[j];
|
||
|
arr[j]=temp;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
|
||
|
printf("The numbers in the sorted array are:\n");
|
||
|
for(i=0;i<n;i++){
|
||
|
printf("%d\n",arr[i]);
|
||
|
}
|
||
|
|
||
|
// binary search
|
||
|
|
||
|
printf("Enter the number you want to search: ");
|
||
|
scanf("%d",&a);
|
||
|
|
||
|
int max = n-1;
|
||
|
int min = 0;
|
||
|
|
||
|
for(i=0;i<n;i++)
|
||
|
{
|
||
|
c=(max+min)/2;
|
||
|
if(a==arr[c])
|
||
|
{
|
||
|
printf("The element is at position %d. \n",c);
|
||
|
flag = 1;
|
||
|
break;
|
||
|
}
|
||
|
if(a<arr[max] && a>arr[c])
|
||
|
min=c;
|
||
|
if(a<arr[c] && a>arr[min])
|
||
|
max=c;
|
||
|
}
|
||
|
|
||
|
if(flag){
|
||
|
printf("The number has been found.\n");
|
||
|
}else{
|
||
|
printf("The number does not exist in this array.\n");
|
||
|
}
|
||
|
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
|