ššIntermediate
Sort Array Using Bubble Sort
Sort using bubble sort
Bubble Sort repeatedly swaps adjacent elements if they are in wrong order. After each pass, the largest element "bubbles up" to its correct position.
Program Code
bubble_sort.c
C
1#include <stdio.h>23int main() {4 int n;5 6 printf("Enter number of elements: ");7 scanf("%d", &n);8 9 int arr[n];10 printf("Enter %d elements: ", n);11 for (int i = 0; i < n; i++) {12 scanf("%d", &arr[i]);13 }14 15 // Bubble Sort16 for (int i = 0; i < n - 1; i++) {17 for (int j = 0; j < n - i - 1; j++) {18 if (arr[j] > arr[j + 1]) {19 // Swap20 int temp = arr[j];21 arr[j] = arr[j + 1];22 arr[j + 1] = temp;23 }24 }25 }26 27 printf("Sorted array: ");28 for (int i = 0; i < n; i++) {29 printf("%d ", arr[i]);30 }31 printf("\n");32 33 return 0;34}Output
Enter number of elements: 5
Enter 5 elements: 64 34 25 12 22
Sorted array: 12 22 25 34 64
Time Complexity: O(n²) - Not efficient for large arrays. Space Complexity: O(1) - Sorts in place.
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials