pages

Thursday, 29 July 2021

Bubble sort in c-language | c-programming

Bubble sort in c language.

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
The bubble sort algorithm isn't efficient as its both average-case as well as worst-case complexity are O(n2).
Bubble sort is a beginners sorting program, it is most learned, but not most used widely due to its time complexity.

Bubble sort algorithm

Start at index zero, compare the element with the next one (a[0] & a[1] (a is the name of the array)), and swap if a[0] > a[1]. Now compare a[1] & a[2] and swap if a[1] > a[2]. Repeat this process until the end of the array. After doing this, the largest element is present at the end. 


#include<stdio.h>
#include<conio.h>
void  bubble_sort(int A[],int N);
void main()
{
    int A[]={44,64,34,2,54};
    int i;
    bubble_sort(A,5);
    for(i=0;i<5;i++)
    {
        printf("%d ",A[i]);
    }
    getch();
}
void bubble_sort(int A[],int N)
{
    int round,j,temp;
    for(round=1;round<=N-1;round++)
    {
        for(j=0;j<=N-1-round;j++)
        {
            if(A[j]>A[j+1])
            {
                temp=A[j];
                A[j]=A[j+1];
                A[j+1]=temp;
            }
        }
    }
}


output:-





For more c-programming .....