Sorting: selection and insertion sort · الفرز: الفرز بالاختيار والفرز بالإدراج
Putting an array in order
- Sorting means putting the values of an array in order, usually from small to large.
- On the AP CSA exam you must be able to write and trace two sorts: selection sort and insertion sort.
- You also need to trace (but not write) a third sort: merge sort. We look at all three here.
ترتيب مصفوفة
- الترتيب يعني وضع قيم المصفوفة في ترتيب، عادة من الصغير إلى الكبير.
- في امتحان AP CSA، يجب أن تتمكن من كتابة وتتبع نوعين من الترتيب: ترتيب الاختيار وترتيب الإدراج.
- تحتاج أيضًا إلى تتبع (ولكن ليس كتابة) ترتيب ثالث: ترتيب الدمج. سننظر إلى الثلاثة هنا.
Selection sort: the idea
- Walk through the array from left to right.
- At each spot
i, find the smallest value in the part that is still unsorted (fromito the end). - Swap that smallest value into spot
i. Now0..iis sorted. - Repeat until the whole array is in order.
ترتيب الاختيار: الفكرة
- مر عبر المصفوفة من اليسار إلى اليمين.
- عند كل موقع
i، جد أصغر قيمة في الجزء الذي لا يزال غير مرتب (منiإلى النهاية). - بدّل تلك الأصغر قيمة إلى الموقع
i. الآن0..iمرتب. - كرر حتى تصبح المصفوفة بأكملها مرتبة.
public class Sorter {
public static void selectionSort(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
int min = i; // index of smallest so far
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[min]) {
min = j; // found a smaller value
}
}
int temp = a[min]; // swap a[i] and a[min]
a[min] = a[i];
a[i] = temp;
}
}
}
Selection sort: a trace
- Let us sort
{5, 2, 4, 1, 3}. The bold part is already sorted. - Each pass picks the smallest value from the rest and swaps it to the front.
ترتيب الاختيار: تتبع
- لنقم بترتيب
{5, 2, 4, 1, 3}. الجزء الغامق مرتب بالفعل. - كل دورة تختار أصغر قيمة من الباقي وتبدلها للأمام.
start: [5, 2, 4, 1, 3]
i=0 smallest=1 → swap a[0],a[3]: [1 | 2, 4, 5, 3]
i=1 smallest is already 2 → no move: [1, 2 | 4, 5, 3]
i=2 smallest=3 → swap a[2],a[4]: [1, 2, 3 | 5, 4]
i=3 smallest=4 → swap a[3],a[4]: [1, 2, 3, 4 | 5]
done: [1, 2, 3, 4, 5]
Insertion sort: the idea
- Think of holding playing cards and adding one card at a time into the right place.
- Start at index
1. Call this value the key. - Slide bigger values on the left one step to the right, until the key fits.
- Drop the key into the gap. Now everything to the left is sorted.
ترتيب الإدراج: الفكرة
- تخيل أنك تمسك بأوراق اللعب وتضيف ورقة واحدة في كل مرة في المكان الصحيح.
- ابدأ من الفهرس
1. سمّ هذه القيمة المفتاح. - حرك القيم الأكبر على اليسار خطوة واحدة إلى اليمين، حتى يتناسب المفتاح.
- ضع المفتاح في الفراغ. الآن كل شيء على اليسار مرتب.
public class Sorter {
public static void insertionSort(int[] a) {
for (int i = 1; i < a.length; i++) {
int key = a[i]; // the value to place
int j = i - 1;
while (j >= 0 && a[j] > key) { // shift bigger values right
a[j + 1] = a[j];
j = j - 1;
}
a[j + 1] = key; // drop key into the gap
}
}
}
Insertion sort: a trace
- Sort
{5, 2, 4, 1, 3}again. The bold part stays sorted as we go. - The
keyis the value we are inserting on each pass.
ترتيب الإدراج: تتبع
- رتب
{5, 2, 4, 1, 3}مرة أخرى. الجزء الغامق يبقى مرتبًا أثناء المرور. - الـ
keyهو القيمة التي نقوم بإدراجها في كل دورة.
start: [5, 2, 4, 1, 3]
i=1 key=2 → shift 5 right, place 2: [2, 5 | 4, 1, 3]
i=2 key=4 → shift 5 right, place 4: [2, 4, 5 | 1, 3]
i=3 key=1 → shift 5,4,2 right, place 1: [1, 2, 4, 5 | 3]
i=4 key=3 → shift 5,4 right, place 3: [1, 2, 3, 4, 5]
done: [1, 2, 3, 4, 5]
Merge sort: trace only
- Merge sort uses recursion (lesson 15). You do not write it on the exam, but you must trace it.
- Split the array in half again and again, until each piece has one value.
- Merge pairs of pieces back together, always keeping them in order.
ترتيب الدمج: تتبع فقط
- ترتيب الدمج يستخدم الاستدعاء الذاتي (الدرس 15). لا تكتبه في الامتحان، لكن عليك تتبعه.
- قسّم المصفوفة إلى نصفين مرارًا وتكرارًا، حتى يصبح لكل جزء قيمة واحدة.
- دمج أزواج الأجزاء معًا، مع الحفاظ دائمًا على ترتيبها.
Merge sort: a trace
- One value is already "sorted". Merging two sorted pieces gives a bigger sorted piece.
- Selection and insertion sort are slow on big arrays (they do about n² steps).
- Merge sort is faster on big arrays (about n·log n steps). That is why it matters.
ترتيب الدمج: تتبع
- قيمة واحدة "مرتبة" بالفعل. دمج جزئين مرتبين يعطي جزءًا أكبر مرتبًا.
split: [5, 2, 4, 1]
[5, 2] [4, 1]
[5] [2] [4] [1]
merge: [2, 5] [1, 4]
merge: [1, 2, 4, 5]
- ترتيب الاختيار وترتيب الإدراج بطيئان على المصفوفات الكبيرة (يقومان بحوالي n² خطوات).
- ترتيب الدمج أسرع على المصفوفات الكبيرة (حوالي n·log n خطوات). ولهذا السبب فهو مهم.
Common mistakes
- Selection and insertion sort are both O(n²).
- Trace a small array by hand to check your sort.
أخطاء شائعة
- ترتيب الاختيار وترتيب الإدراج كلاهما O(n²).
- تتبع مصفوفة صغيرة يدويًا للتحقق من ترتيبك.
Now you try
- Each task gives you a method skeleton with a TODO. Sort the array in place (change
aitself). - A hidden Harness sorts several arrays and checks the result.
- Press Run to compile, then Check answer.
الآن جرب بنفسك
- كل مهمة تعطيك هيكلاً لطريقة مع TODO. رتب المصفوفة محليًا (غيّر
aنفسه). - Harness مخفي يرتب عدة مصفوفات ويتحقق من النتيجة.
- اضغط تشغيل للتجميع، ثم فحص الإجابة.
Selection / insertion sort · الفرز بالاختيار / الفرز بالإدراج
Sorting compares and swaps until the list is ordered. · الفرز يقارن ويتبادل حتى ترتب القائمة.
Complete selectionSort(int[] a) so it sorts the array in place from small to large, using selection sort. The checker tests several arrays. · أكمل selectionSort(int[] a) لفرز المصفوفة محليًا من الصغير إلى الكبير باستخدام الفرز بالاختيار. يختبر الفاحس عدة مصفوفات.
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.
Complete insertionSort(int[] a) so it sorts the array in place from small to large, using insertion sort. The checker tests several arrays. · أكمل insertionSort(int[] a) لفرز المصفوفة محليًا من الصغير إلى الكبير باستخدام الفرز بالإدراج. يختبر الفاحس عدة مصفوفات.
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.
Complete isSorted(int[] a) returning true if the array is in order from small to large (each item is <= the next), else false. An empty or one-item array counts as sorted. · أكمل isSorted(int[] a) بإرجاع true إذا كانت المصفوفة مرتبة من الصغير إلى الكبير (كل عنصر هو <= التالي)، وإلا false. المصفوفة الفارغة أو ذات العنصر الواحد تُحسب مرتبة.
Click Run to see the output here. · اضغط تشغيل لرؤية المخرجات هنا.