Lecture241 merge

# Lecture241 merge - Merge Sort Algorithm Merge sort has two...

This preview shows pages 1–3. Sign up to view the full content.

Lecture 1 -- 1 Computer Science I - Martin Hardwick Merge Sort Algorithm Merge sort has two phases. First it divides the data into smaller and smaller lists until they are  size 2 or 1 Second as it returns it merges all the lists using a merge algorithm Consider the following data set. – 78 45 34 20 18 15 96 10 The first two sub lists for merging will be – 45 78 – 20 34 After merge – 20 34 45 78 The next two sub-lists are – 15 18 – 10 96 After merge – 10 15 18 96 Final merge yields – 10 15 18 20 34 45 78 96

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Lecture 1 -- 2 Computer Science I - Martin Hardwick Merge vector <int>  merge(  vector <int>list1, vector <int>list2) // Merge two sorted lists { vector <int> result; int i1 = 0; int i2 = 0; while (i1 < list1.size() || i2 < list2.size()) { if (list1[i1] < list2[i2])       result.push_back (list1[i1++]); else      result.push_back (list2[i2++]);     }     else { while (i1 < list1.size())     result.push_back (list1[i1++]); while (i2 < list2.size())     result.push_back (list2[i2++]);     } } return result; } This algorithm picks the smallest item from each list. When it reaches the end of one list it then fills in the remaining items from the other list.
This is the end of the preview. Sign up to access the rest of the document.

## Lecture241 merge - Merge Sort Algorithm Merge sort has two...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online