Home >Backend Development >C++ >Bubble Sort in C
Sorting is a necessary concept we need to learn in any programming language. Mostly sorting is done on arrays involving numbers and is a stepping stones to mastering the art of techniques to traversing and accessing data from arrays.
The type of sorting technique we are going to talk about in today's article will Bubble Sort.
Bubble sorting is a simple sorting algorithm that works by repeatedly swapping adjacent elements if they are in wrong order. This method of sorting an array is not suitable for large data sets as the time complexity for average and worst case scenarios is very high.
Below is the implementation of the bubble sort. It can be optimized by stopping the algorithm if the inner loop didn’t cause any swap.
// Easy implementation of Bubble sort #include <stdio.h> int main(){ int i, j, size, temp, count=0, a[100]; //Asking the user for size of array printf("Enter the size of array you want to enter = \t"); scanf("%d", &size); //taking the input array through loop for (i=0;i<size;i++){ printf("Enter the %dth element",i); scanf("%d",&a[i]); } //printing the unsorted list printf("The list you entered is : \n"); for (i=0;i<size;i++){ printf("%d,\t",a[i]); } //sorting the list for (i = 0; i < size - 1; i++) { count = 1; for (j = 0; j < size - i - 1; j++) { if (a[j] > a[j + 1]) { //swapping elements temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; count = 1; } } // If no two elements were swapped by inner loop, // then break if (count == 1) break; } // printing the sorted list printf("\nThe sorted list is : \n"); for (i=0;i<size;i++){ printf("%d,\t",a[i]); } return 0; }
**
Time Complexity: O(n2)
Auxiliary Space: O(1)
Do comment if you have any queries !!
And all discussions will be appreciated :)
The above is the detailed content of Bubble Sort in C. For more information, please follow other related articles on the PHP Chinese website!