العودة إلى الدراسة

المحاضرة 5 من 10

45 دقيقة تقريبًا

Selection Sort and Insertion Sort, One Move at a Time

Trace the same two arrays, understand the role of each variable, and count comparisons, swaps, and shifts separately.

تصفّح الدفتر
Step 1 of 8 · Understand

Selection Sort: Find the Smallest Remaining Value

Goal: Understand how selecting one minimum fixes one position.

We want to sort [5,6,3,4,2] in ascending order. Search the whole array for its smallest value: 2. Exchange it with the first value, 5. The array becomes [2,6,3,4,5]. Exchanging two values is a swap.

The first position is now correct. Search only the remaining part, choose its smallest value, and put that value at the start of that part. This is Selection Sort. Each round fixes one more position.

Read the code after the idea
الكود أو الخطوات
#include <utility>

void selectionSort(int a[], int n) {
    for (int i = 0; i < n - 1; ++i) {
        int minIndex = i;
        for (int j = i + 1; j < n; ++j) {
            if (a[j] < a[minIndex]) {
                minIndex = j;
            }
        }
        std::swap(a[i], a[minIndex]);
    }
}

Here n is the array length and is a nonnegative integer. a[i] means the value at index i; the first index is 0.

minIndex stores the position of the smallest value found so far, not the value itself. For the value 2 at index 4, it stores 4. We need that position when calling swap. The two parts are inside the same array; we do not create a second array.

Quick check · predict, then try

Before the First Selection Round

We have not finished searching for the minimum yet. How many elements are in the part whose final positions have already been fixed?

Choose your prediction

Remember: Search the remaining part first. Swap only after the search is complete.

موضعك محفوظ تلقائيًا
مصادر الدرس وملاحظات المراجعة

يعتمد ترتيب الموضوعات والأمثلة على صفحات 30–45 من الدفتر. نسبة الدفتر إلى الدكتور غير مؤكدة. الشرح والتفاعلات التعليمية صياغة مساعدة، وليست نقلًا حرفيًا.

شرح عربي مساعد يعتمد ترتيب الموضوعات والأمثلة في الدفتر المستلم. المصدر الأصلي محفوظ، وتفاصيل التصحيحات والإضافات في ملاحظات المراجعة. لا يوجد دليل يؤكد اسم الدكتور أو مطابقة محاضرات الدفتر للتسجيلين.

نسبة الدفتر إلى الدكتور غير مؤكدة. أمثلة Selection وInsertion الأصلية محفوظة. ملاحظات التصحيح: صفحة37 تذكر15 swap وهذا لا يطابق الكود؛ لخمس قيم10 مقارنات و4 استدعاءات swap. في صفحة39 يجب إعلان j بحيث يبقى متاحًا بعد for. average case يحتاج توزيعًا مفترضًا، وليس كل ترتيب شبه مرتب متوسطًا. الجزء المحسوم أول Selection حجمه0، وفق تصحيح القناة. الأنشطة التفاعلية إضافات تعليمية؛ مطابقة المصدر ليست معتمدة تلقائيًا.

تصفّح صفحات هذا الدرس من الدفتر
خطوة صغيرة. فهم أعمق.ألجولاب · دفتر شخصي للدراسة