Title: For Friday
1For Friday
- Read Weiss, chapter 7, sections 8-10
- Homework
- Chapter 7, exercises 4, 11, and 12
2Exam 1
- Will be one week from Friday
- Will cover material through quicksort
3Programming Assignment 2
4Shellsort
- Whats the concept?
- h-sorting
- increment sequence
- Shells sequence 1, 2, 4, 8,
- Hibbards sequence 1, 3, 7, 15,
- best sequence known 1, 5, 19, 41, 109,
5Performance of Shellsort
6Heapsort
7Heapsort
- Use max heaps instead of min heaps
- Use BuildHeap to turn the array into a heap
- Use deleteMax to remove items from the beginning
of the array, continually moving them to the end
of the tree
8Performance of Heapsort
9Mergesort
10Mergesort
- void MergeSort(int arr, int temp, int left,
- int right)
-
- if (left lt right)
- int center (left right)/ 2
- // sort left half
- MergeSort(arr, temp, left, center)
- // sort right half
- MergeSort(arr, temp, center1, right)
- // merge left and right halves
- Merge(arr, temp, left, center1, right)
-
11- void Merge(int arr, int temp, int curLeft,
- int curRight, int endRight)
-
- int endLeft curRight 1
- int curTemp curLeft
- int numElems endRight startLeft 1
- // Main loop
- while (curLeft lt endLeft curRight lt
endRight) - if ( arrcurLeft lt arrcurRight)
- tempcurTemp arrcurLeft
- else
- tempcurTemp arrcurRight
- while (curLeft lt endLeft) // finish left
- tempcurTemp arrcurLeft
- while (curRight lt endRight) // finish right
- tempcurTemp arrcurRight
- // copy back to arr
- for (int i 0 i lt numElems i,
endRight--) - aendRight tempArrayendRight
12Performance of Mergesort
13Bottom-up Mergesort
14Quicksort
- Basic concept
- Were going to select a pivot
- Were going to swap items into either smaller or
large than the pivot, giving us two portions
(partitions) of the array - Were going to sort each resulting partition
using quicksort
15void quicksort(int a, int left, int right)
int i, j, v, temp if (right - left gt 0) //
at least two items in the partition v
aright //v is the pivot i left - 1 //
1 to the left of the beginning j right
// 1 to the right of where search starts while
(true) // infinite loop while (ai lt v)
// pre-increment i until ai is gt the pivot
while (a--j gt v) // pre-decrement j until
aj is lt the pivot if (i gt j) break
//if i and j have crossed -- get out of the loop
temp ai // otherwise, swap ai and
aj ai aj aj temp //
i and j have crossed, so swap ai and the pivot
aright ai ai v // the pivot
is now in place at i // now call quicksort on
the two partitions quicksort(a, left, i-1) //
left partition quicksort(a, i1, right) //
right partition
16Performance of Quicksort
17Improving Quicksort