Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP 171 Data Structures and Algorithms Tutorial 4 In-Class Exercises: Algorithm Design.

Similar presentations


Presentation on theme: "COMP 171 Data Structures and Algorithms Tutorial 4 In-Class Exercises: Algorithm Design."— Presentation transcript:

1 COMP 171 Data Structures and Algorithms Tutorial 4 In-Class Exercises: Algorithm Design

2 Exercises 2.3-6 (p.37) Observe that the while loop of the Insertion- sort procedure uses a linear search to scan (backward) through the sorted subarray A[0..i-1]. Can we use a binary search instead to improve the overall worst-case running time of insertion sort to Θ (n ㏒ n)?

3 InsertionSort(A) for i ← 1 to size(A)-1 key ← A[i] j ← i – 1 while j ≧ 0 and A[j] > key A[j + 1] ← A[j] j ← j – 1 end while A[j + 1] ← key end for i end InsertionSort

4 BinarySearch(A, left, right, s_value) if left ≦ right then middle ←  (left + right) / 2  if A[middle] = s_value then return middle else if A[middle] > s_value then BinarySearch(A, left, middle-1, s_value) else BinarySearch(A, middle+1, right, s_value) end if else return –1; end if end BinarySearch

5 Exercises 2.3-7 (p.37) Describe a Θ(n ㏒ n)-time algorithm that, given a set of S of n integers and another integer x, determines whether or not there exist two elements in S whose sum is exactly x.

6 Exercises 2-4 (p.39) Let A[1..n] be an array of n distinct numbers. If i A[j], then the pair (i, j) is called an inversion of A. –List the five inversions of the array {2, 3, 8, 6, 1} –What array with elements from the set {1, 2, …, n} has the most inversions? How many does it have?

7 –What is the relationship between the running time of insertion sort and the number of inversions in the input array? Justify your answer. –Given an algorithm that determines the number of inversions in any permutation on n elements in Θ(n ㏒ n) worst-case time. (Hint: Modify merge sort)

8 mergesort(A, left, right) if left < right then middle ←  (left + right) / 2  mergesort(A, left, middle) mergesort(A, middle+1, right) merge(A, left, middle+1, right) end if end mergesort

9 merge(A, p, q, r) n 1 ← q – p n 2 ← r – q + 1 create array L[0..n 1 ], R[0..n 2 ] for i ← 0 to n1-1 do L[i] ← A[p+i] for j ← 0 to n2-1 do R[j] ← A[q+j] L[n 1 ] ← R[n 2 ] ← ∞ I ← j ← 0 for k ← p to r if L[I] < R[j] then A[k] ← L[i] i ← i + 1 else A[k] ← R[j] j ← j + 1 end if end for k end merge


Download ppt "COMP 171 Data Structures and Algorithms Tutorial 4 In-Class Exercises: Algorithm Design."

Similar presentations


Ads by Google