📘 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.
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 8सारांश
- Selection sort: repeatedly find the minimum and swap it forward.
- Insertion sort: shift larger elements and insert each in place.
💻 Live Code Editor
Is page ke program yahan ready hain — chalाएं, badlें aur seekhें. Bina kuch install kiye.
Powered by OneCompiler. Editor mein code apne aap aa jata hai — Run dabaakर output dekhें.
Agar load na ho to naye tab mein kholें.