The program sorts an array in ascending order based on the given input. There are various sorting algorithms to achieve this functionality Such as Selection Sort, Insertion sort and more . In this, We’ll be using Bubble Sort algorithm.
Bubble sort is one of the simplest and most popular algorithms, but inefficient. It repeatedly compares each element with their adjacent elements and performs swapping if required.
Pseudocode
FOR i=0 to Array.Length FOR j=Array.Length-1 to i IF A[j]< A[j-1]) Swap A[j] and A[j-1] END IF END FOR END FOR
C program to sort an array using Bubble Sort in Ascending Order
#include<conio.h> #include<stdio.h> #define size 5 void main() { int arr[size],i,j,temp; printf("Please enter elements: \n "); for(i=0;i<=size-1;i++) { scanf("%d",&arr[i]); } for(i=0;i<=size-1;i++) { for(j=size-1;j>i;j--) { if(arr[j]<arr[j-1]){ temp = arr[j]; arr[j] =arr[j-1]; arr[j-1] = temp; } } } printf(" \n Entered Elements :"); for(i=0;i<=size-1;i++) { printf("\n %d ",arr[i]); } getch(); }
Output:
How does Bubble Sort program work?
It requires a constant amount O(1) of additional memory space and O(n2) comparisons in the worst case and average case to sort an array.
However, this sorting technique is too slow and impractical if we compare it with Insertion sort