Bubble Sort in C Language
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. In C language, an implementation of the bubble sort algorithm can be as follows:
#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
The bubbleSort
function takes an integer array arr
and its length n
as arguments. It iterates over the array multiple times, comparing each adjacent element and swapping them if they are in the wrong order. The largest element will “bubble” up to the end of the array after each iteration. The loop runs n-1
times since the last element will be sorted automatically after n-1
iterations.
The main
function creates an integer array and calls the bubbleSort
function to sort it. Finally, it prints the sorted array to the console.
Note that the worst-case time complexity of bubble sort is O(n^2), and it is not very efficient for large arrays. However, it has a small overhead and can be very efficient for small or partially sorted arrays.