CS 46B - Lecture 11

Cover page image

Pre-class reading

Merge Sort

Merge Sort Example

Merge Sort

public void sort()
{
   if (a.length <= 1) return;
   int [] first = new int[a.length / 2];
   int[] second = new int[a.length - first.length];
   // Copy the first half of a into first, the second half into second 
   . . .
   MergeSorter firstSorter = new MergeSorter(first);
   MergeSorter secondSorter = new MergeSorter(second);
   firstSorter.sort();
   secondSorter.sort();
   merge(first, second);
}

Lecture 11 Clicker Question 1

Look at the first while loop of the merge method. Which of the following is true when the loop is complete?

  1. All elements of first have been added to a
  2. All elements of second have been added to a
  3. All elements of first or second have been added to a
  4. Both first and second contain some elements that haven't been added to a

Lecture 11 Clicker Question 2

Consider the merge method, and assume that a has n elements. What is the big-Oh efficiency of the merge method?

  1. O(1)
  2. O(n)
  3. O(n log n)
  4. O(n2)

Analyzing the Merge Sort Algorithm

n Merge Sort (milliseconds) Selection Sort (milliseconds)
10,000 40 786
20,000 73 2,148
30,000 134 4,796
40,000 170 9,192
50,000 192 13,321
60,000 205 19,299

Merge Sort Timing vs. Selection Sort

Analyzing the Merge Sort Algorithm

Analyzing the Merge Sort Algorithm

Analyzing Merge Sort Algorithm

Analyzing Merge Sort Algorithm

Merge Sort Vs Selection Sort

Lecture 11 Clicker Question 3

Consider an array of length n and another of length 1000n. What is most likely true about selection sort and merge sort?

  1. With selection sort and merge sort, the longer array takes 1000 times as long as with the original array.
  2. With selection sort and merge sort, the longer array takes 1,000,000 times as long as with the original array.
  3. With selection sort, the longer array takes 1,000,000 times as long, but with merge sort, it takes about the same time as with the original array
  4. With selection sort, the longer array takes 1,000,000 times as long, but with merge sort, it takes about 10,000  the same time as with the original array

The Quicksort Algorithm

The Quicksort Algorithm

public void sort(int from, int to)
{
   if (from >= to) return; 
   int p = partition(from, to);
   sort(from, p);
   sort(p + 1, to); 
}

The Quicksort Algorithm

The Quicksort Algorithm

private int partition(int from, int to)
{
   int pivot = a[from]; 
   int i = from - 1;
   int j = to + 1;
   while (i < j)
   { 
      i++;
      while (a[i] < pivot) i++;
      j--;
      while (a[j] > pivot) j--; 
     if (i < j) swap(i, j);  
   }
   return j;
}