Writing Methods AP Computer Science A Merge Sort






- Slides: 6
Writing Methods AP Computer Science A
Merge Sort // postcondition: merges(combines) list 1 // and list 2 into one sorted list public int[ ] merge( int[ ] list 1, int[ ] list 2) { } Here are some examples. list 1= 1 2 5 8 list 2= 2 5 9 10 returns : 1 2 2 5 5 8 9 10 OR list 1 = 4 5 6 7 12 list 2 = 4 9 10 11 returns 4 4 5 6 7 9 10 11 12
First of all, think of how you would do this by hand. • • list 1= 1 2 5 8 list 2= 2 5 9 10 returns : 1 2 2 5 5 8 9 10 We start at the beginning of each list. List 1 has the value of 1 and list 2 has the value of 2. Since 1 is less, we copy one into the new list=1. Next in list 1 we check 2 and in list 2 we check 2. The are both the same, so let’s copy both into the array. List=1, 2, 2. Next, we check 5 in list 1 and 5 in list 2. Again they are the same so we copy both. List=1, 2, 2, 5, 5. Next we check 8 in list 1 and 9 in list 2. 8 is smaller so we copy 8. List=1, 2, 2, 5, 5, 8. Since we have reached the end of List 1 we can just copy everything else in list 2. List=1, 2, 2, 5, 5, 8, 9, 10. The end.
Let’s work through another example. • • list 1 = 4 5 6 7 12 list 2 = 4 9 10 11 returns 4 4 5 6 7 9 10 11 12 First we start at the beginning of list 1 and the beginning of list 2. We see 4 and 4. Since they are the same then copy both. List: 4, 4. Next we compare 5 in list 1 and 9 in list 2. 5 is smaller so copy 5. List: 4, 4, 5. Next we compare 6 in list 1 and 9 in list 2. 6 is smaller, so copy 6. List 4, 4, 5, 6. Next we compare 7 in list 1 and 9 in list 2. 7 is smaller so copy 7. List: 4, 4, 5, 6, 7. Next we compare 12 in list 1 and 9 in list 2. 9 is smaller so copy 9. List: 4, 4, 5, 6, 7, 9. Next we compare 12 in list 1 to 10 in list 2. 10 is smaller so copy 10. List: 4, 4, 5, 6, 7, 9, 10. Next we compare 12 in list 1 to 11 in list 2. 11 is smaller so copy 11. List: 4, 4, 5, 6, 7, 9, 10, 11. We have reached the end of list 2, so copy the rest of list 1 which only has 12 left. List: 4, 4, 5, 6, 7, 9, 10, 11, 12.
What do you think the merge method would look like? • Remember list 1 and list to are arrays, so you have to access the elements in each array using brackets and indexes. ( list 1[0], list 1[i]) • Don’t forget to return the merged list at the end. • Make sure all your variables are the proper type. // postcondition: merges(combines) list 1 // and list 2 into one sorted list public int[ ] merge( int[ ] list 1, int[ ] list 2) { }
See word document for solution • That’s it for today. Read over pg 236 in 5 steps to 5.