Lecture 4.Pptx
Lecture 4.Pptx
Selection Sort
How It Works?
• Find the smallest element in the array and swap it
with the first element.
• Move to the second position, find the next smallest
element, and swap it with the second element.
• Repeat this process until the entire array is sorted.
2
Code
#include <iostream>
using namespace std;
int main() {
}
3
Bubble Sort
How It Works?
• Compare adjacent elements and swap if they are in
the wrong order.
• After each full pass, the largest element moves to its
correct position.
• Repeat the process until no swaps are needed.
4
Code
#include <iostream>
using namespace std;
int main() {
int arr[] = {5, 3, 8, 4, 2};
int n = sizeof(arr) / sizeof(arr[0]);
return 0;
} 5
Insertion Sort
How It Works?
• Start from the second element and compare it with
previous elements.
• Shift larger elements to the right and insert the
selected element in the correct place.
• Repeat until the entire array is sorted.
6
Code
#include <iostream>
using namespace std;
int main() {
int arr[] = {9, 5, 1, 4, 3};
int n = sizeof(arr) / sizeof(arr[0]);
return 0;
}
7
Quick Sort
How It Works?
• Pick a pivot element (usually last or random).
• Arrange elements smaller than the pivot to its left and
greater than the pivot to its right (Partitioning step).
• Recursively apply the same process to left and right
subarrays.
8
Code
#include <iostream>
using namespace std;
quickSort(arr, 0, n - 1);
return 0;
}
10
Final Comparison Table
11