Inspiration
Bubble Sort: A Simple Sorting Algorithm
What is Bubble Sort?
Bubble Sort is one of the simplest sorting algorithms. It repeatedly compares adjacent elements in a list and swaps them if they are in the wrong order. This process is repeated until the list is completely sorted.
How Does It Work?
The algorithm works like this:
- Start at the beginning of the list.
- Compare each pair of adjacent elements.
- Swap them if they are out of order.
- Repeat the process for all elements until no swaps are needed.
Why is it Called Bubble Sort?
The largest elements "bubble up" to the end of the list with each pass, similar to bubbles rising in water.
Advantages
- Simplicity: Easy to understand and implement.
- Visualization: Ideal for demonstrating the basics of sorting.
Disadvantages
- Inefficient: Has a time complexity of O(n²), making it slow for large datasets.
Bubble Sort Code in C
Here’s how Bubble Sort is implemented in C:
#include <stdio.h>
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int 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;
}
Log in or sign up for Devpost to join the conversation.