C Program for Binary Search and Bubble Sort Using Recursion

C Program for Binary Search and Bubble Sort Using Recursion

C Program For Selection Sort: Click Now

Write a C Program for Binary Search Using Recursion

#include<stdio.h>

#include<stdlib.h>

 void BinarySearch(int arr[], int num, int first, int last)

{

  if(first > last)

   {

  printf(“Number is not found”);

  } 

   else 

   {

  int mid;

 //calculate mid

  mid = (first + last)/2;

  //if value is found at mid position

   if(arr[mid]==num)

     {

  printf(“Element is found at index %d “,mid);

            exit(0);

}

   else if(arr[mid]>num)

        {

 //Recursive call

   BinarySearch(arr, num, first, mid-1);

   }

else

        {

  //Recursive call

         BinarySearch(arr, num, mid+1, last);

        }

  }

}

main()

{

 int arr[] = {2,5,7,9,12,15,18};

   //Search 9 in a sorted array

   int num = 9;

  int first =0 , last = (sizeof(arr)/sizeof(arr[0]))-1;

  BinarySearch(arr, num, first, last);

}

Write a C Program For Bubble Sort Using Recursion

#include <stdio.h>
 
// Utility function to swap values at
two indices in the array
 
void swap(int arr[], int i, int j)
{
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}
 
// Function to print n elements
of the array arr
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
{
        printf(“%d “, arr[i]);
    }
}
 
// Recursive function to perform
bubble sort on subarray arr[i..n]
 
void bubbleSort(int arr[], int n)
{
    for (int i = 0; i < n 1; i++)
{
        if (arr[i] > arr[i + 1]) {
            swap(arr, i, i + 1);
        }
    }
    if (n 1 > 1) {
        bubbleSort(arr, n 1);
    }
}
 
// Bubble sort algorithm
int main(void)
{
    int arr[] = { 3, 5, 8, 4, 1, 9, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    bubbleSort(arr, n);
    printArray(arr, n);
 
    return 0;
}
 
Note: At the run time if you can find
any error please Comment, i will
definitely solve the issue and
update the code.
Thank you

 

Leave a Comment