Objectives ● Understand and explain how the merge sort algorithm works. ● Understand and explain how the bubble sort algorithm works. ● Compare and contrast merge sort and bubble sort algorithms. Sorting ● When we’re managing data, at some point it may need to be sorted ● All sorted data is based on an order (alphabetical, numerical, etc) ● This makes it quicker to find things in lists, arrays and databases ● Example: Finding the student whose ID number is 1405912 Types of Sorts There are two methods of sorting data in algorithms: ● Merge sort ● Bubble sort Merge Sort The merge sort is like the binary search - the sort splits the data in half and works on each half in turn. The computer sorts the smaller groups before merging the two groups together again, a bit like when we shuffle cards (only we mess up the sort, the computer resets it) How is a merge sort ran? 1.FIrstly, the computer repeatedly splits the data into two halves until each “list” contains only one item of data. 2.Now decomposed, these “lists” can be merged back together, this time in either ascending (A→Z)or descending order (A←Z) Pseudocode If the array is already sorted MergeSort (Array(First..Last)) BEGIN Rounded to the IF Array contains only one element THEN nearest integer RETURN Array ELSE Middle= ((Last + First)/2) LeftSide=MergeSort(Array(FIrst..Middle) RightSide=MergeSort(Array(Middle+1..Last)0 Result=Merge(LeftSide,RightSide) RETURN Result ENDIF END MergeSort Bubble Sort The bubble sort comes from the idea of stones settling in a tank: larger stones sink to the bottom while the small ones rise to the top. How is a bubble sort ran? 1.A bubble sort compares the first two items, checks which is larger and puts the large one first 2.The next pair is checked, and so on… 3.If there have been any position changes, the whole process is repeated until the computer can go from start to finish and there are no changed to be made. 4.At this point, the data is in descending order. Pseudocode FOR i from 1 to N For x from 0 to N - 1 IF y[x]>y[x+1] SWAP (y[x], y[x+1]) Comparing Merge & Bubble Bubble Merge
Efficiently handle big data sets? No Yes
Speed Usually slower Faster
Space used in memory Stable (never changes since Variable (splits the data in items are just swapped) two)