Merge sort b

Preview:

DESCRIPTION

 

Citation preview

Merge sort

Let’s start with an unsorted list

Divide the list into two lists

Divide that list up again

Divide that list up again

And again...

A single item list must be sorted✓

go to the next list, a single item list must be sorted✓

jjii

KKNow take that pair and merge

jjii

KK

Look down both lists taking the smallest

jjii

✓KK

When both lists run out you have a sorted list

jjii Now this pair is sorted

✓Do the same with the next pair

✓Each is a list of one item (so sorted)

jjii

KK We merge again

jjii

KK

Creating a new sorted list

Now we have two lists of pairs...

So we merge them

jjii

KK

Look down both lists taking the smallest

jjii

KK

jjii

KK

Look down both lists taking the smallest

jjii

KK

Look down both lists taking the smallest

jjii

KK

Look down both lists taking the smallest

jjii KK

Look down both lists taking the smallest

the list is sorted and you can begin the next quarter

A single item list must be sorted✓

A single item list must be sorted✓

jjii KK Merge this pair

jjii

KK

Pick the smaller item

jjii KKWhen both lists run out you have a sorted list

Sort the next pair

A single item list must be sorted

A single item list must be sorted

Merge the single item lists

jjii KK Merge this pair

jjii KK

Pick the smaller item

jjii KKPick the smaller item

Now we have two lists of pairs...

ii

jj KKSo we merge them

ii

jj KK

Pick the smaller item

ii jj

KKPick the smaller item

ii jj KK

Pick the smaller item

ii jj

KK

Pick the smaller item

the pairs lists are now merged

ii jj KK

Now we merge the quarters

ii

jj KK

Pick the smaller item

ii jj KK

and move on

ii jj KK

Pick the smaller item

ii jj KK

and move on

ii jj KK

Pick the smaller item

ii jj KK

and move on

ii jj KK

Pick the smaller item

ii jj KK

and move on

The first half is now sorted

Quickly we do the other half

Divide...

and Divide...

and Divide until the lists can be no smaller

Merge pairs...

Merge quaters

Finally the second half is sorted

A final merge of both halves makes the list sorted

ii jj KK

Merging lists takes as long as the list (order(N))

You do this log(N) timesMaking algorithm Order (N log(N))

ii jj KK

Merging lists takes as long as the list (order(N))

You do this log(N) timesMaking algorithm Order (N log(N))

Merging lists takes as long as the list (order(N))

You do this log(N) timesMaking algorithm Order (N log(N))

Pity you need extra space to ‘merge’ into otherwise it would be pretty cool