Sorting Algorithms Explained – Bubble Sort, Selection Sort, and Insertion Sort with Examples
Sorting Algorithms Explained – Bubble Sort, Selection Sort, and Insertion Sort with Examples
Sorting is one of the most important concepts in Data Structures and Algorithms. Almost every application needs sorted data, whether it is search results, ranking systems, or databases. In this article, we will learn three basic sorting algorithms: Bubble Sort, Selection Sort, and Insertion Sort in a simple way.
What is Sorting?
Sorting means arranging data in a specific order, usually in ascending or descending order. For example, arranging numbers from smallest to largest or names in alphabetical order.
1. Bubble Sort
Bubble Sort is the simplest sorting algorithm. It repeatedly compares adjacent elements and swaps them if they are in the wrong order. This process continues until the array becomes sorted.
How Bubble Sort Works
- Compare first two elements
- Swap if they are in the wrong order
- Move to the next pair
- Repeat until no swaps are needed
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;
}
}
}
}
2. Selection Sort
Selection Sort works by finding the smallest element in the array and placing it at the beginning. Then it finds the second smallest and places it at the second position, and so on.
How Selection Sort Works
- Find the minimum element
- Swap it with the first position
- Repeat for the remaining elements
void selectionSort(int arr[], int n) {
for(int i = 0; i < n-1; i++) {
int minIndex = i;
for(int j = i+1; j < n; j++) {
if(arr[j] < arr[minIndex])
minIndex = j;
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
3. Insertion Sort
Insertion Sort works the same way you sort playing cards in your hand. It takes one element at a time and inserts it into its correct position.
How Insertion Sort Works
- Take one element
- Compare it with previous elements
- Insert it in the correct position
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;
}
}
Time Complexity Comparison
| Algorithm | Best | Average | Worst |
|---|---|---|---|
| Bubble Sort | O(n) | O(n²) | O(n²) |
| Selection Sort | O(n²) | O(n²) | O(n²) |
| Insertion Sort | O(n) | O(n²) | O(n²) |
Interview Importance
Sorting algorithms are frequently asked in interviews to test your understanding of loops, comparisons, and algorithm efficiency.
Conclusion
Bubble Sort, Selection Sort, and Insertion Sort are basic but very important sorting techniques. Once you understand these, learning advanced sorting algorithms like Merge Sort and Quick Sort becomes much easier.
Next Post: Merge Sort and Quick Sort Explained with Diagrams and Code
Comments
Post a Comment