Sorting Algorithms in C
In the previous lesson, you learned how Binary Search Trees keep data ordered.
In many programs, data is not automatically ordered. We must explicitly arrange it in a specific order.
This process is called Sorting.
What Is Sorting?
Sorting is the process of arranging data in a particular order.
Common orders:
- Ascending (small → large)
- Descending (large → small)
Why Is Sorting Important?
Sorting helps in:
- Fast searching
- Better data presentation
- Efficient algorithms
Example: Searching is much faster in sorted data.
Common Sorting Algorithms
- Bubble Sort
- Selection Sort
- Insertion Sort
These algorithms are easy to understand and form the base for advanced sorts.
Bubble Sort
Bubble Sort repeatedly compares adjacent elements and swaps them if needed.
Largest elements slowly “bubble” to the end.
#include <stdio.h>
int main() {
int a[5] = {5, 3, 4, 1, 2};
int i, j, temp;
for (i = 0; i < 5 - 1; i++) {
for (j = 0; j < 5 - i - 1; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (i = 0; i < 5; i++)
printf("%d ", a[i]);
return 0;
}
Selection Sort
Selection Sort selects the smallest element and places it at the correct position.
#include <stdio.h>
int main() {
int a[5] = {64, 25, 12, 22, 11};
int i, j, min, temp;
for (i = 0; i < 5 - 1; i++) {
min = i;
for (j = i + 1; j < 5; j++) {
if (a[j] < a[min])
min = j;
}
temp = a[min];
a[min] = a[i];
a[i] = temp;
}
for (i = 0; i < 5; i++)
printf("%d ", a[i]);
return 0;
}
Insertion Sort
Insertion Sort builds the sorted list one element at a time.
It works well for small or nearly sorted data.
#include <stdio.h>
int main() {
int a[5] = {8, 3, 5, 2, 4};
int i, key, j;
for (i = 1; i < 5; i++) {
key = a[i];
j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
for (i = 0; i < 5; i++)
printf("%d ", a[i]);
return 0;
}
Basic Time Complexity Idea
You don’t need to memorize formulas now. Just remember:
- Bubble, Selection, Insertion → Slow for large data
- Used mainly for learning and small datasets
Real-World Example
Think of sorting marks of students:
- Teachers want highest to lowest
- Sorting makes ranking easy
Mini Practice
- Take 10 numbers from user
- Apply any sorting method
- Display sorted list
Quick Quiz
Q1. What is sorting?
Arranging data in a specific order
Q2. Which sort swaps adjacent elements?
Bubble Sort
Q3. Which sort selects minimum element?
Selection Sort
Q4. Which sort works well for nearly sorted data?
Insertion Sort
Q5. Is sorting important in real programs?
Yes