Bubble Sort using Array
Write a C Program to implement Bubble Sort using Array. Here’s simple C Program to implement Bubble Sort using Array in C Programming Language.
The simplest sorting algorithm is bubble sort. The C bubble sort works by iterating down an array to be sorted from the first element to the last, comparing each pair of elements and switching their positions if necessary.
This process is repeated as many times as necessary, until the array is sorted.
Since the worst case scenario is that the array is in reverse order, and that the first element in sorted array is the last element in the starting array, the most exchanges that will be necessary is equal to the length of the array.
Here is a simple example:
Given an array 23154 a bubble sort would lead to the following sequence of partially sorted arrays: 21354, 21345, 12345.
First the 1 and 3 would be compared and switched, then the 4 and 5. On the next pass, the 1 and 2 would switch, and the array would be in order.
Both worst case and average case complexity is O (n2) , where n is the number of items.
Below is the source code for C Program to implement Bubble Sort using Array which is successfully compiled and run on Windows System to produce desired output as shown below :
SOURCE CODE : :
/* C Program to implement Bubble Sort using Array */ #include<stdio.h> int main() { int n,i,j,temp; printf("Enter the size of Array : "); scanf("%d",&n); int a[n]; printf("Enter elements : \n"); for(i=0;i<n;i++) { printf("Enter %d element : ",i+1); scanf("%d",&a[i]); } for(i=1;i<n;++i) { for(j=0;j<(n-i);++j) if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } printf("\nArray after c bubble sort: "); for(i=0;i<n;i++) { printf(" %d ",a[i]); } return 0; }
OUTPUT : :
/* C Program to implement Bubble Sort using Array */ Enter the size of Array : 7 Enter elements : Enter 1 element : 4 Enter 2 element : 1 Enter 3 element : 3 Enter 4 element : 6 Enter 5 element : 9 Enter 6 element : 0 Enter 7 element : 4 Array after c bubble sort: 0 1 3 4 4 6 9
Above is the source code for C Program to implement Bubble Sort using Array which is successfully compiled and run on Windows System.The Output of the program is shown above .
If you found any error or any queries related to the above program or any questions or reviews , you wanna to ask from us ,you may Contact Us through our contact Page or you can also comment below in the comment section.We will try our best to reach up to you in short interval.
Thanks for reading the post….