Lecture 20 - Searching and Sorting

Problems

For today’s problems, start by devising an algorithm and writing it in pseudocode. Do not rely on any built-in functions or methods that are specific to Python. Question 0 and its answer is given to you as an example of what pseudocode for an answer might look like.

  1. Write an algorithm to return the index of the first occurrence of a value v in a list L.

    Pseudocode:

    find(v, L):
        for each element in L:
            if the element is equal to v:
                return the index of v
        return -1
  2. [This is the same as Problem 4 from L19]. Write an algorithm that returns the index of the first occurrence of of a value v in a sorted list L, in such a way that you index into the list less than len(sorted_lst) times. This means a brute-force approach of checking all elements won’t work. To avoid this, you’ll need to think of a way to take advantage of the fact that the list is sorted.
  3. Write an algorithm that takes a list L and returns a new list containing the same elements, but arranged in sorted (increasing) order.
  4. Write an algorithm that takes a list L and sorts its contents in place; this means the contents of the given list are rearranged without being copied into a new list.