C Program for Sorting an Array using Bubble Sort

By | 12.09.2017

Sorting an Array using Bubble Sort


Write a C Program for Sorting an Array using Bubble Sort.  Here’s a simple C Program for Sorting an Array using Bubble Sort in C Programming Language.


Bubble Sort


Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.

Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse sorted.

Best Case Time Complexity: O(n). Best case occurs when array is already sorted.

Auxiliary Space: O(1)


Also Read : : C Program for Sorting an Array using Selection Sort

Below is the source code for C Program for Sorting an Array using Bubble Sort which is successfully compiled and run on Windows System to produce desired output as shown below :


SOURCE CODE : :


/* C Program for Sorting an Array using Bubble Sort */

#include <stdio.h>
#define MAX 100

int main()
{
        int arr[MAX],i,j,temp,n,xchanges;

        printf("\nEnter the number of elements : ");
        scanf("%d",&n);

        for(i=0; i<n; i++)
        {
                printf("Enter element %d : ",i+1);
                scanf("%d",&arr[i]);
        }

        /*Bubble sort*/
        for(i=0; i<n-1; i++)
        {
                xchanges=0;
                for(j=0; j<n-1-i; j++)
                {
                        if(arr[j] > arr[j+1])
                        {
                                temp = arr[j];
                                arr[j] = arr[j+1];
                                arr[j+1] = temp;
                                xchanges++;
                        }
                }
                if(xchanges==0) /*If list is sorted*/
                        break;
        }

        printf("\nSorted list is :\n");
        for(i=0; i<n; i++)
                printf("  %d  ",arr[i]);
        printf("\n");

        return 0;
}/*End of main()*/

OUTPUT: :


/* C Program for Sorting an Array using Bubble Sort */

Enter the number of elements : 6
Enter element 1 : 5
Enter element 2 : 2
Enter element 3 : 4
Enter element 4 : 1
Enter element 5 : 3
Enter element 6 : 4

Sorted list is :
  1    2    3    4    4    5

Process returned 0

If you found any error or any queries related to the above program or any questions or reviews, you wanna 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 a short interval.


Thanks for reading the post…


Recommended Posts : :

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments