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
#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]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int arr[] = {5, 2, 9, 1, 5};
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;
}
Output:
Sorted array: 1 2 5 5 9
4. Example: Selection Sort
#include <stdio.h>
void selectionSort(int arr[], int n) {
for(int i = 0; i < n-1; i++) {
int min_idx = i;
for(int j = i+1; j < n; j++)
if(arr[j] < arr[min_idx])
min_idx = j;
int temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: ");
for(int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output:
Sorted array: 11 12 22 25 64
5. Example: Insertion Sort
#include <stdio.h>
void insertionSort(int arr[], int n) {
for(int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while(j >= 0 && arr[j] > key) {
arr[j+1] = arr[j];
j--;
}
arr[j+1] = key;
}
}
int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);
insertionSort(arr, n);
printf("Sorted array: ");
for(int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Output:
Sorted array: 5 6 11 12 13
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