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.
סידור מערך
- חיפוש ליניארי הוא O(n); בינארי הוא O(log n).
- בבחן 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 נסתר סוורט מספר מערכים ובודק את התוצאה.
- לחץ על Run להתקפלה, ולאחר מכן לחץ על Check answer.
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. · לחץ על הרץ כדי לראות את התוצא כאן.