Professional Documents
Culture Documents
Data Structures II
#2
Heap Sort
What is Heap??
The (binary) heap data structure is an array object that we
can view as a nearly complete binary tree.
- Rightchild(i) = 2*i+1
1
There are two kinds of binary heaps: max-heaps and min-heaps.
In both kinds, the values in the nodes satisfy a heap property.
Max-heap Min-heap
for every node other than root for every node other than root,
, A[PARENT(i)] ≥ A(i) A[PARENT(i)] ≤A(i)
The root has the largest key The root has the smallest key
Max Heap Example Min Heap Example
2
Max Heapify Algorithm
3
Example Calling Max Heapify(A,2)
4
Complexity of BUILD-MAX-HEAP
5
Example for Build Max Heap
6
The heapsort algorithm
The heap sort algorithm then repeats this process for the max-heap
of size n -1 down to a heap of size 2.
7
Complexity of BUILD-MAX-HEAP
The HEAPSORT procedure takes time O(n lg n), since the call to
BUILD-MAX-HEAP takes time O(n) and each of the n -1 calls
to MAX-HEAPIFY takes time O(lg n)
so total running time =O(n)+O(n lg n) O(n lg n)
Heap sort Example
8
Merge Sort
A sorting algorithm based on divide and conquer.
Because we are dealing with sub problems we state the
sub problem as sorting a subarray A[p…r]. Initily p=1 and
r=n but this values change as we recurse through sub
problems to sort A[p…r]
9
Merge Algorithm that merges two sorted lists
into one sorted List.
10
Example for merge sort
11
Analyzing merge sort running time
For simplicity assume n is power of 2 the base case
occurs when n=1
When n≥2 time for merge sort steps
Divide: just compute q as the average of p and r O(1)
Conquer: Recursively solve 2 sub problems each of size
n/2
Combine: Merge n element sub array takes O(n)
12
Insertion Sort
Example:
13
The operation of INSERTION-SORT on the array
A = {5, 2, 4, 6, 1, 3}.
14
Selection Sort
Selection-Sort(A)
for i = 1 to A.length
// Find min. value among a[i], a[i+1], ..., a[n-1]
min_j i;
for j = i+1 to n
if a[j] < a[min_j]
min_j j;
Exchange a[i] a[min_j]
Bubble Sort
15
Quick Sort
16
17
Example: Pivot element is 5
18
Complexity of quick sort
- Average case running time : when the array
divided into two nearly equal parts
-
- So we write the Quick sort recurrence as following:
T (n) =2T (n/2) +n
T (1) =1
By Solving this recurrence so the merge sort
algorithm is O (n log n)
19