Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. The algorithm gets its name because smaller elements "bubble" to the top of the list.
#include<stdio.h> void bubbleSort(int[], int); int main(){ int n, arr[50]; printf("Enter the number of elements: "); scanf("%d",&n); printf("Enter %d elements: ",n); for(int i=0;i<n;i++){ scanf("%d",&arr[i]); } bubbleSort(arr, n); printf("Sorted array: "); for(int i=0;i<n;i++){ printf("%d ",arr[i]); } return 0; } void bubbleSort(int arr[], int n){ int i, j, temp; for(i=0;i<n-1;i++){ for(j=0;j<n-i-1;j++){ if(arr[j]>arr[j+1]){ temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } }
Sample Input and Output:
Enter the number of elements: 7
Enter 7 elements: 6 3 12 9 15 21 18
Sorted array: 3 6 9 12 15 18 21
Enter the number of elements: 7
Enter 7 elements: 6 3 12 9 15 21 18
Sorted array: 3 6 9 12 15 18 21