Activity4 - SortSearch-Programming Exercises
Activity4 - SortSearch-Programming Exercises
a. Use Quicksort, sort array A in ascending order. List down the values that were chosen as the pivot after each call
of Partition.
b. Use Bubble sort algorithm, sort the array A in ascending order. In the process of sorting the array A, how many
times comparison (i.e., the “if condition” is checked) and swap (i.e., exchanging 2 values) operations were
performed?
c. Referring to insertion sort algorithm and assume that the insertion sort algorithm was modified to sort a set of
values in descending order. Sort the elements in array A. In the process of sorting the array, how many times
comparison and swap operations were performed?
d. Using Selection sort algorithm, sort the array A in ascending order. In the process of sorting the array, how many
times comparison and swap operations were performed?
Problem #2: Discuss/show the situation(s) in which Quicksort exhibits O(n 2).
Problem #4: Consider the numerical 30-True/False (or Yes or No) Questions game. In this game, Player 1 thinks of a
number in the range 1 to n. Player 2 has to figure out (or guess) this number by asking the fewest number of true/false
(yes or no) questions. Assume that nobody cheats!
a. What is the optimal strategy in finding out Player 1’s number if n is known?
b. What is a good strategy in finding out Player 1’s number if n is not known?
Problem #5: Suppose that you are given a sorted sequence of distinct integers {a1,a2,…,an}. Give an O(lg n) algorithm to
determine whether there exists an i index such as ai=i. For example, in {−10,−3,3,5,7}, a3=3. In {2,3,4,5,6,7}, there is no
such i.
Problem #6: The Grinch is given the job of partitioning 2n players into two teams of n players each. Each player has a
numerical rating that measures how good he/she is at the game. He seeks to divide the players as unfairly as possible,
so as to create the biggest possible talent imbalance between team A and team B. Show how the Grinch can do the job
in O(n log2 n) time.
Problem #7: For each of the following problems, give an algorithm that finds the desired numbers within the given
amount of time.
For the example, S={6,13,19,3,8}, 19−3 maximizes the difference, while 8−6 minimizes the difference.
a. Let S be a sorted array of n integers. Give an algorithm (or write a function) that finds the pair x,y ∈
S that maximizes |x−y|. Your algorithm must run in O(1) worst-case time.
b. Let S be an unsorted array of n integers. Give an algorithm that finds the pair x,y ∈ S that minimizes |x−y|, for x≠y.
Your algorithm must run in O(n lg n) worst-case time.