Sorting(Bubble Sort) and Searchng(Binary search) in C

Example program 2

Here this part of the code sorts the numbers in the array in ascending order. It checks if number 1 is greater than the next number. If so it exchanges the 2 numbers.

for(int i=0;i<n-1;i++)
    {
        for(int j=0;j<n-i-1;j++)
        {
            if(arr[j]>arr[j+1])
            {
                swap=arr[j];
                arr[j]=arr[j+1];
                arr[j+1]=swap;

            }
        }
    }

Here this part of the code searches the required number using bubble sort. Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list, comparing adjacent elements, and swapping them if they are in the wrong order. The process is repeated until the list is sorted.

 for(int i=0;i<n;i++){
        if(se==arr[d])
        {printf("Yes\n");
            break;
        }
        else if(se>arr[d]){
            d=d+1;
            printf("d=%d\n",arr[d]);
        }
        else if(se<arr[d]){
            d=d-1;
            printf("d=%d\n",arr[d]);
        }

Here is the main code.

#include<stdio.h>
#include<ctype.h>

int main()
{
    printf("Enter the number of elements in the array\n");
    int n;
    scanf("%d",&n);
    int arr[n];
    printf("Enter the elements in the array\n");
    for(int i=0;i<n;i++){
        scanf("%d",&arr[i]);
    }
    int se;
    int swap;
    for(int i=0;i<n-1;i++)
    {
        for(int j=0;j<n-i-1;j++)
        {
            if(arr[j]>arr[j+1])
            {
                swap=arr[j];
                arr[j]=arr[j+1];
                arr[j+1]=swap;

            }
        }
    }
    printf("Sorted list in ascending order\n");
    for(int i=0;i<n;i++){
        printf("%d\n",arr[i]);
    }
    printf("Enter the number to search \n");
    scanf("%d",&se);
    int d=n/2;
    int max=n;
    int min=0;
    for(int i=0;i<n;i++){
        if(se==arr[d])
        {printf("Yes\n");
            break;
        }
        else if(se>arr[d]){
            d=d+1;
            printf("d=%d\n",arr[d]);
        }
        else if(se<arr[d]){
            d=d-1;
            printf("d=%d\n",arr[d]);
        }
    }
}

Thanks for reading this blog hope this was helpful. Don't forget to follow.

Enjoy learning...