- Administrivia; 5 weeks to go?! We have to go faster!
- Efficiency; when does it matter? Run time vs. development time (and bugs!!).
- Representation
- The array
- start index
- end index
- Example: head after the first time through 4 3 5 2 7 8 1 2
- Merge sort pseudocode
mergeSort(List aList) {
if (size>1) {
split aList roughly in half creating head and tail
mergeSort(head)
mergeSort(tail)
merge head and tail
}
}
- merge(list1, list2)
Assuming you have created an array of length n outside of any loop, named result
...
while (both list1 and list2 have more elements) {
if (head of list1 <= head of list2) {
add head of list1 to result (and delete it!)
} else { // bigger
add head of list2 to tail of result
}
}
if (list1 not empty) {
add everything from list1 to result
}
} else {
add everything from list2 to result
}
- Example: mergesorting 3, 2, 1, 6, 7, 8, 5, 4
- Watch out! There is no way to do it in place (that I can think of) and if you allocate arrays uncarefully, you will get results like I did (below) -- see debug in MergeSort...
T I M I N G S O R T S !
bubble merge better? quiok
n=20 t=1 t=0 t=0 t=0
n=40 t=0 t=0 t=0 t=0
n=80 t=0 t=0 t=0 t=0
n=160 t=1 t=0 t=0 t=1
n=320 t=2 t=1 t=0 t=0
n=640 t=6 t=1 t=0 t=0
n=1280 t=2 t=0 t=1 t=0
n=2560 t=10 t=1 t=1 t=0
n=5120 t=31 t=4 t=1 t=0
n=10240 t=128 t=14 t=1 t=0
n=20480 t=551 t=34 t=2 t=1
n=40960 t=2242 t=212 t=3 t=4
n=81920 t=8847 t=705 t=7 t=7
n=163840 t=35883 t=2189 t=15 t=16
n=327680 slow t=13172 t=33 t=35
n=655360 slow t=34721 t=71 t=74
n=1310720 slow slow t=154 t=154
n=2621440 slow slow t=320 t=323
n=5242880 slow slow t=655 t=668
n=10485760 slow slow t=1379 t=1433
n=20971520 slow slow t=2905 t=3013
n=41943040 slow slow t=6004 t=6241
n=83886080 slow slow t=12407 t=12562
n=167772160 slow slow t=25164 t=26050
n=335544320 slow slow
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space!
- Counting sort! O(n)!
pseudocode
tableSort(List aList) {
//count em
create an array of counters
for each element, e {
counter[e]++
}
// spew
clear aList
for each counter (counter[i]) {
emit that many i's (i.e. insert that many into aList)
}
}