{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

# Lecture-23 - MergeSortAlgorithm Merge sort has two phases q...

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

Computer Science I - Martin Hardwick Lecture 1 -- 1 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
Computer Science I - Martin Hardwick Lecture 1 -- 2 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 (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. Consider List1: 18 23 45 78 List2: 19 21 80 90 List 1 will be consumed first Result: 18 19 21 23 45 78 I1 = 4 I2 = 2 We then add 80 and 90 from list 2 Result:18 19 21 23 45 78 80  90 I1 = 4 I2 = 4
Computer Science I - Martin Hardwick Lecture 1 -- 3 Data management issues The given algorithm is not very efficient. It adds too many items to too many vectors using push_back.

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 11

Lecture-23 - MergeSortAlgorithm Merge sort has two phases q...

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

View Full Document
Ask a homework question - tutors are online