📘 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 8

Insertion 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

Summary

  • 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 8

Insertion 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 करें।
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

\n