sorting
sorting
2
Using Java Sorting Methods
3
Using Java Sorting Methods (continued)
4
Selection Sort
5
Selection Sort (continued)
6
Bubble Sort
7
Analysis of Bubble Sort
8
Insertion Sort
9
Insertion Sort Algorithm
10
Analysis of Insertion Sort
11
Comparison of Quadratic Sorts
12
Shell Sort: A Better Insertion Sort
• Shell sort is a type of insertion sort but with O(n^(3/2)) or
better performance
• Named after its discoverer, Donald Shell
• Divide and conquer approach to insertion sort
• Instead of sorting the entire array, sort many smaller
subarrays using insertion sort before sorting the entire
array
13
Analysis of Shell Sort
14
Merge Sort
15
Merge Algorithm
• Merge Algorithm
• Access the first item from both sequences
• While not finished with either sequence
• Compare the current items from the two sequences, copy the
smaller current item to the output sequence, and access the
next item from the input sequence whose item was copied
• Copy any remaining items from the first sequence to
the output sequence
• Copy any remaining items from the second sequence
to the output sequence
16
Analysis of Merge
17
Algorithm and Trace of Merge Sort
18
mergeSort example
19
Algorithm and Trace of Merge Sort
(continued)
20
Simple MergeSort Algorithm
function merge_sort(m)
var list left, right, result
if length(m) ≤ 1
return m
21
Merge function
• function merge(left,right)
• var list result
• while length(left) > 0 and length(right) > 0
• if first(left) ≤ first(right)
• append first(left) to result
• left = rest(left)
• else
• append first(right) to result
• right = rest(right)
• end while
• if length(left) > 0
• append left to result
• else
• append right to result
• return result
22
• In sorting n objects, merge sort has an average and worst-case
performance of O(n log n). If the running time of merge sort for a list
of length n is T(n), then the recurrence T(n) = 2T(n/2) + n follows
from the definition of the algorithm (apply the algorithm to two lists of
half the size of the original list, and add the n steps taken to merge
the resulting two lists). The closed form follows from the master
theorem.
• In the worst case, merge sort does an amount of comparisons equal
to or slightly smaller than (n ⌈lg n⌉ - 2⌈lg n⌉ + 1), which is between
(n lg n - n + 1) and (n lg n + n + O(lg n)). [1]
• For large n and a randomly ordered input list, merge sort's expected
(average) number of comparisons approaches α·n fewer than the
worst case where
• In the worst case, merge sort does about 39% fewer comparisons
than quicksort does in the average case; merge sort always makes
fewer comparisons than quicksort, except in extremely rare cases,
when they tie, where merge sort's worst case is found
simultaneously with quicksort's best case. In terms of moves, merge
sort's worst case complexity is O(n log n)—the same complexity as
quicksort's best case, and merge sort's best case takes about half
as many iterations as the worst case.
23
Heapsort
24
Algorithm for In-Place Heapsort
25
Quicksort
• Developed in 1962
• Quicksort rearranges an array into two parts so that all
the elements in the left subarray are less than or equal to
a specified value, called the pivot
• Quicksort ensures that the elements in the right subarray
are larger than the pivot
• Average case for Quicksort is O(n log n)
26
Quicksort (continued)
27
28
Algorithm for Partitioning
29
Revised Partition Algorithm
30
Testing the Sort Algorithms
31
The Dutch National Flag Problem
32
The Dutch National Flag Problem
33
Chapter Review
• Comparison of several sorting algorithms were made
• Three quadratic sorting algorithms are selection sort,
bubble sort, and insertion sort
• Shell sort gives satisfactory performance for arrays up to
5000 elements
• Quicksort has an average-case performance of O(n log
n), but if the pivot is picked poorly, the worst case
performance is O(n*n)
• Merge sort and heapsort have O(n log n) performance
34
Chapter Review (continued)
35
Bubble sort
• Compare each element (except the last one) with its
neighbor to the right
• If they are out of order, swap them
• This puts the largest element at the very end
• The last element is now in the correct and final place
• Compare each element (except the last two) with its
neighbor to the right
• If they are out of order, swap them
• This puts the second largest element next to last
• The last two elements are now in their correct and final places
• Compare each element (except the last three) with its
neighbor to the right
• Continue as above until you have no unsorted elements on the
left
36
Example of bubble sort
7 2 8 5 4 2 7 5 4 8 2 5 4 7 8 2 4 5 7 8
2 7 8 5 4 2 7 5 4 8 2 5 4 7 8 2 4 5 7 8
2 7 8 5 4 2 5 7 4 8 2 4 5 7 8 (done)
2 7 5 8 4 2 5 4 7 8
2 7 5 4 8
37
Code for bubble sort
• public static void bubbleSort(int[] a) {
int outer, inner;
for (outer = a.length - 1; outer > 0; outer--) { //
counting down
for (inner = 0; inner < outer; inner++) { //
bubbling up
if (a[inner] > a[inner + 1]) { // if out of order...
int temp = a[inner]; // ...then swap
a[inner] = a[inner + 1];
a[inner + 1] = temp;
}
}
}
}
38
Analysis of bubble sort
• for (outer = a.length - 1; outer > 0; outer--) {
for (inner = 0; inner < outer; inner++) {
if (a[inner] > a[inner + 1]) {
// code for swap omitted
}
}
}
• Let n = a.length = size of the array
• The outer loop is executed n-1 times (call it n, that’s close enough)
• Each time the outer loop is executed, the inner loop is executed
• Inner loop executes n-1 times at first, linearly dropping to just
once
• On average, inner loop executes about n/2 times for each
execution of the outer loop
• In the inner loop, the comparison is always done (constant
time), the swap might be done (also constant time)
• Result is n * n/2 * k, that is, O(n2/2 + k) = O(n2) 39
Loop invariants
40
Selection sort
41
Example and analysis of selection sort
42
Code for selection sort
public static void selectionSort(int[] a) {
int outer, inner, min;
for (outer = 0; outer < a.length - 1; outer++) { // outer counts
down
min = outer;
for (inner = outer + 1; inner < a.length; inner++) {
if (a[inner] < a[min]) {
min = inner;
}
// Invariant: for all i, if outer <= i <= inner, then a[min]
<= a[i]
}
// a[min] is least among a[outer]..a[a.length - 1]
int temp = a[outer];
a[outer] = a[min];
a[min] = temp;
// Invariant: for all i <= outer, if i < j then a[i] <= a[j]
}
}
43
Invariants for selection sort
44
Insertion sort
3 4 7 12 14 14 20 21 33 38 10 55 9 23 28 16
temp
less than
10
10
3 4 7 10 12 14 14 20 21 33 38 55 9 23 28 16
sorted
46
Analysis of insertion sort
47