COMP 171 Data Structures and Algorithms - PowerPoint PPT Presentation

About This Presentation
Title:

COMP 171 Data Structures and Algorithms

Description:

... x, determines whether or not there exist two elements in S whose sum is exactly x. ... with elements from the set {1, 2, ..., n} has the most inversions? ... – PowerPoint PPT presentation

Number of Views:28
Avg rating:3.0/5.0
Slides: 10
Provided by: vincen94
Category:

less

Transcript and Presenter's Notes

Title: COMP 171 Data Structures and Algorithms


1
COMP 171Data 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 A0..i-1. Can we use
    a binary search instead to improve the overall
    worst-case running time of insertion sort to T
    (n?n)?

3
  • InsertionSort(A)
  • for i ? 1 to size(A)-1
  • key ? Ai
  • j ? i 1
  • while j ? 0 and Aj gt key
  • Aj 1 ? Aj
  • j ? j 1
  • end while
  • Aj 1 ? key
  • end for i
  • end InsertionSort

4
  • BinarySearch(A, left, right, s_value)
  • if left ? right then
  • middle ? ?(left right) / 2?
  • if Amiddle s_value then
  • return middle
  • else if Amiddle gt s_value then
  • BinarySearch(A, left, middle-1, s_value)
  • else
  • BinarySearch(A, middle1, right, s_value)
  • end if
  • else
  • return 1
  • end if
  • end BinarySearch

5
Exercises 2.3-7 (p.37)
  • Describe a T(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 A1..n be an array of n distinct numbers. If
    i lt j and Ai gt Aj, 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
    T(n?n) worst-case time. (Hint Modify merge sort)

8
  • mergesort(A, left, right)
  • if left lt right then
  • middle ? ?(left right) / 2?
  • mergesort(A, left, middle)
  • mergesort(A, middle1, right)
  • merge(A, left, middle1, right)
  • end if
  • end mergesort

9
  • merge(A, p, q, r)
  • n1 ? q p
  • n2 ? r q 1
  • create array L0..n1, R0..n2
  • for i ? 0 to n1-1 do Li ? Api
  • for j ? 0 to n2-1 do Rj ? Aqj
  • Ln1 ? Rn2 ? 8
  • I ? j ? 0
  • for k ? p to r
  • if LI lt Rj then
  • Ak ? Li
  • i ? i 1
  • else
  • Ak ? Rj
  • j ? j 1
  • end if
  • end for k
  • end merge
Write a Comment
User Comments (0)
About PowerShow.com