Sorting Algorithms in C (Complete Guide with Examples)
This tutorial explains sorting algorithms in C, which are used to arrange data in a specific order (ascending or descending). It covers Bubble Sort, Selection Sort, Insertion Sort, Merge Sort, and Quick Sort with practical examples for better understanding.
1. What is Sorting
- Sorting is the process of arranging elements in a specific order
- Ascending order: smallest to largest
- Descending order: largest to smallest
- Sorting improves searching efficiency
2. Common Sorting Algorithms
| AlgorithmTime Complexity (Average)Description | ||
| Bubble Sort | O(n²) | Repeatedly swaps adjacent elements |
| Selection Sort | O(n²) | Selects minimum/maximum and swaps |
| Insertion Sort | O(n²) | Inserts each element into correct position |
| Merge Sort | O(n log n) | Divide and conquer method, stable |
| Quick Sort | O(n log n) | Divide and conquer, selects pivot, faster in practice |
3. Example: Bubble Sort
Output:
4. Example: Selection Sort
Output:
5. Example: Insertion Sort
Output:
6. Key Points to Remember
- Sorting improves search efficiency and organization
- Simple sorts: Bubble, Selection, Insertion – easy to implement, O(n²)
- Advanced sorts: Merge, Quick – efficient, O(n log n), suitable for large data
- Choose algorithm based on data size, memory, and stability requirements