Created
October 30, 2020 09:32
-
-
Save AakashCode12/5a86fcef03904b2118adb02cba8010c0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
//Linear Search Function (DONE) | |
int linearSearch(int arr[], int val, int n) | |
{ | |
int valPosition = -1; | |
for (int i = 0; i < n; i++) | |
{ | |
if (val == arr[i]) | |
{ | |
valPosition = i; | |
break; | |
} | |
} | |
return valPosition; | |
} | |
//Binary Search Function | |
int binarySearch(int arr[], int val, int n) | |
{ | |
//BUBBLE SORTING | |
int temp = 0; | |
for (int i = 0; i < n - 1; i++) | |
{ | |
for (int j = i; j < n; j++) | |
{ | |
if (arr[i] > arr[j]) | |
{ | |
temp = arr[j]; | |
arr[j] = arr[i]; | |
arr[i] = temp; | |
} | |
} | |
} | |
//ACTUAL ALGO STARTS HERE | |
int valPosition = -1; | |
int l = 0; | |
int middle; | |
while (l <= n) | |
{ | |
middle = l + (n - l) / 2; | |
if (arr[middle] == val) | |
{ | |
return middle; | |
} | |
if (arr[middle] < val) | |
{ | |
l = middle + 1; | |
} | |
else | |
{ | |
n = middle - 1; | |
} | |
} | |
return valPosition; | |
} | |
// main Function (Done) | |
void main() | |
{ | |
int n, option, val, ans; | |
printf("********************----Searching an Element Program----********************"); | |
printf("\nEnter the Size of Array : "); | |
scanf("%d", &n); | |
int arr[n]; | |
//input from array | |
for (int i = 0; i < n; i++) | |
{ | |
printf("\nEnter the Element : "); | |
scanf("%d", &arr[i]); | |
} | |
//menu | |
do | |
{ | |
printf("\nSelect the Algorithm"); | |
printf("\n1)Linear Search"); | |
printf("\n2)Binary Search"); | |
printf("\n3)Exit "); | |
printf("\nEnter your OPTION : "); | |
scanf("%d", &option); | |
switch (option) | |
{ | |
case 1: | |
printf("\nEnter the Value you want to search : "); | |
scanf("%d", &val); | |
ans = linearSearch(arr, val, n); | |
if (ans == -1) | |
{ | |
printf("\nELEMENT NOT PRESENT\n"); | |
} | |
else | |
{ | |
printf("\nThe Position of the Value is %d \n", ans); | |
} | |
break; | |
case 2: | |
printf("\nEnter the Value you want to search : "); | |
scanf("%d", &val); | |
ans = binarySearch(arr, val, n); | |
if (ans == -1) | |
{ | |
printf("\nELEMENT NOT PRESENT\n"); | |
} | |
else | |
{ | |
printf("\nThe Position of the Value in Sorted Array is %d\n", ans); | |
} | |
break; | |
case 3: | |
break; | |
default: | |
printf("\nINVALID OPTION CHOOSEN\n"); | |
break; | |
} | |
} while (option != 3); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment