Sorting Part 2
Sorting Part 2
Chapter 10
Sorting Algorithms
Objectives
• Search algorithms
– Concerned with number of key (item) comparisons
• Sorting algorithms
– Concerned with number of key comparisons and
number of data movements
• Analysis of selection sort – O(n2)
– Function swap
• Number of item assignments: 3(n-1)
– Function minLocation
• Number of key comparisons of O(n2)
FIGURE 10-5 list elements while moving list[4] to its proper place
FIGURE 10-8 list elements while moving list[4] to its proper place
proper
• So far: O(n2)
• The rest: O(nlog2n)
• Quicksort
– Average-case behavior: O(nlog2n)
– Worst-case behavior: O(n2)
• Mergesort behavior: always O(nlog2n)
– Uses divide-and-conquer technique to sort a list
– Partitions list into two sublists
• Sorts sublists
• Combines sorted sublists into one sorted list
• Difference between mergesort and quicksort
– How list is partitioned
Data Structures Using C++ 2E 42
Mergesort: Linked List-Based Lists
(cont’d.)
• Ex: list[3] = 50
– list[7] = 20 & list[8] = 10
– list[3] >= list[7] & list[3] >= list[8]
Data Structures Using C++ 2E 52
Heapsort: Array-Based Lists (cont’d.)
• Data given in Figure 10-41
– Can be viewed in a complete binary tree
• Function heapify
– Restores the heap in a subtree
– Implements the buildHeap function
• Converts list into a heap
• Function heapify
– Implements the buildHeap function
• Converts list into a heap
• Chapter 10 – Exercise 1
• Chapter 10 – Exercise 2
• Chapter 10 – Exercise 9
• Chapter 10 – Exercise 10
• Chapter 10 – Exercise 11