📘 Lesson · Lesson 78
Selection & Insertion Sort
Selection & Insertion Sort
Two Simple Sorts
💡 Note
Selection sort picks the smallest and places it first. Insertion sort inserts each element into its correct position.
Selection Sort
C++
int a[] = {5, 2, 8, 1}, n = 4;
for (int i = 0; i < n-1; i++) {
int min = i;
for (int j = i+1; j < n; j++)
if (a[j] < a[min]) min = j;
swap(a[i], a[min]);
}
// a = 1 2 5 8Insertion Sort
C++
int a[] = {5, 2, 8, 1}, n = 4;
for (int i = 1; i < n; i++) {
int key = a[i], j = i - 1;
while (j >= 0 && a[j] > key) { a[j+1] = a[j]; j--; }
a[j+1] = key;
}
// a = 1 2 5 8Summary
- Selection sort: repeatedly find the minimum and swap it forward.
- Insertion sort: shift larger elements and insert each in place.
दो Simple Sorts
💡 Note
Selection sort सबसे छोटा चुनकर पहले रखता है। Insertion sort हर element को उसकी सही जगह insert करता है।
Selection Sort
C++
int a[] = {5, 2, 8, 1}, n = 4;
for (int i = 0; i < n-1; i++) {
int min = i;
for (int j = i+1; j < n; j++)
if (a[j] < a[min]) min = j;
swap(a[i], a[min]);
}
// a = 1 2 5 8Insertion Sort
C++
int a[] = {5, 2, 8, 1}, n = 4;
for (int i = 1; i < n; i++) {
int key = a[i], j = i - 1;
while (j >= 0 && a[j] > key) { a[j+1] = a[j]; j--; }
a[j+1] = key;
}
// a = 1 2 5 8सारांश
- Selection sort: बार-बार minimum ढूंढकर आगे swap करें।
- Insertion sort: बड़े elements shift करके हर एक को जगह पर insert करें।