Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- void printArray(int pArr[], int n) //function to print Array
- {
- printf("\n");
- printf("{");
- for (int i = 0; i < n; ++i) {
- printf("%d",pArr[i]);
- if(i<n-1)
- printf(", ");
- }
- printf("}");
- printf("\n\n");
- }
- void linearSearch(int arr[],int n) //function for linear searching
- {
- int key,flag=0,pos;
- printf("\nEnter key to be searched: ");
- scanf("%d",&key);
- for (int i = 0; i < n; ++i) {
- if(arr[i]==key){
- flag=1;
- pos=i+1;
- break;
- }
- }
- if(flag==1)
- printf("Linear Search successful, Element found at position %d\n",pos);
- else
- printf("Element not found!\n");
- }
- void bubbleSort(int arr[],int n,int sorted_arr[]) // function for bubble sorting
- {
- int temp;
- for (int i = 0; i < n; ++i) {
- sorted_arr[i]=arr[i];
- }
- for (int i = 0; i < n-1; ++i) {
- for (int j = 0; j < n-i-1; ++j) {
- if(sorted_arr[j]>sorted_arr[j+1]){
- temp=sorted_arr[j];
- sorted_arr[j]=sorted_arr[j+1];
- sorted_arr[j+1]=temp;
- }
- }
- }
- printf("\nSorted Array");
- printArray(sorted_arr,n);
- }
- void binarySearch(int arr[],int n) // function for binary searching
- {
- int sorted_arr[n];
- bubbleSort(arr,n,sorted_arr);
- int key,mid,l=0,u=n-1,flag=0;
- printf("\nEnter key to be searched: ");
- scanf("%d",&key);
- while (flag==0 && l<=u){
- mid=(l+u)/2;
- if(arr[mid]==key)
- flag=1;
- if(key<arr[mid])
- u=mid-1;
- else
- l=mid+1;
- }
- if(flag==1)
- printf("Binary Search successful, Element found at position %d\n",++mid);
- else
- printf("Element not found!\n");
- }
- int main()
- {
- int n;
- printf("Enter number of elements in array:\n");
- scanf("%d",&n);
- int arr[n];
- printf("Enter %d numbers:\n",n);
- for (int i = 0; i < n; ++i) {
- scanf("%d",&arr[i]);
- }
- printArray(arr,n);
- while (1) {
- int choice=0;
- printf("\n1. Linear Search\n2. Binary Search\n3. Exit");
- printf("\nEnter your choice: ");
- scanf("%d",&choice);
- switch (choice) {
- case 1:
- linearSearch(arr,n);
- break;
- case 2:
- binarySearch(arr,n);
- break;
- case 3:
- exit(0);
- default:
- printf("Enter a valid argument!\n");
- break;
- }
- }
- }
Add Comment
Please, Sign In to add comment