DATA STRUCTURES AND ALGORITHM – Best Sorting Algorithms – Bubble sort Algorithm Bubble sort in C
DATA STRUCTURES AND ALGORITHM – Best Sorting Algorithms – Bubble sort Algorithm Bubble sort in C
Contents
- 1 Bubble Sort Algorithm in C – Explanation & Code
- 2 How Bubble Sort Works?
- 3 Bubble Sort Algorithm in C
- 4 Explanation of Code
- 5 Example Execution
- 6 Input:
- 7 Sorting Process:
- 8 Output:
- 9 Advantages & Disadvantages
- 10 Alternative Sorting Algorithms
- 11 DATA STRUCTURES AND ALGORITHM – Best Sorting Algorithms – Bubble sort Algorithm Bubble sort in C
- 12 V: Sorting: Bubble sort, Merge sort, Insertion Sort, Selection …
- 13 Data Structures & Algorithms Bubble Sort
Bubble Sort Algorithm in C – Explanation & Code
Bubble Sort is one of the simplest sorting algorithms. It repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the list is sorted.
How Bubble Sort Works?
- Compare adjacent elements.
- Swap them if they are in the wrong order.
- Move to the next pair and repeat.
- Continue this process for every element.
- Repeat the entire process for multiple passes until the array is sorted.
Best Case (Already Sorted): O(n)
Worst Case (Reverse Sorted): O(n²)
Average Case: O(n²)
Stable Sort: Yes
In-Place Algorithm: Yes
Bubble Sort Algorithm in C
Explanation of Code
- Outer Loop: Runs for (n-1) passes to move the largest element to the end.
- Inner Loop: Compares adjacent elements and swaps them if they are out of order.
- Optimization: If no swaps occur in a pass, the array is already sorted, and the loop breaks.
- Function Usage:
bubbleSort()
performs sorting.printArray()
prints the array before and after sorting.
Example Execution
Input:
Sorting Process:
Output:
Advantages & Disadvantages
Advantages:
- Simple and easy to implement.
- Works well for small datasets.
- Stable sorting algorithm.
Disadvantages:
- Inefficient for large datasets.
- Time complexity O(n²) makes it slow compared to other sorting algorithms.
Alternative Sorting Algorithms
- Selection Sort – More efficient but still O(n²).
- Insertion Sort – Efficient for nearly sorted arrays.
- Merge Sort & Quick Sort – More efficient, O(n log n).
Would you like an optimized sorting algorithm like Quick Sort or Merge Sort in C?