Insertion Sort: While Some Elements Unsorted
Insertion Sort: While Some Elements Unsorted
38 45
60 60
66 45
66 79 47 13 74 36 21 94 22 57 16 29 81
the fourth iteration of this loop is shown here
Best case
Worst case
n-1
n-1
n-1
n(n-1)/2
Worst case: the array is sorted in reverse order (so each item
has to be moved to the front of the array)
Time cost:
In the i-th iteration of the outer loop, the inner loop will perform 4i+1
operations
Therefore, the total cost of the inner loop will be 2n(n-1)+n-1
Best case: 7(n-1)
Worst case: 5(n-1)+2n(n-1)+n-1
Bubble Sort
Simplest
sorting algorithm
Idea:
Bubble Sort
1 23 2 56 9 8 10 100
2 1 2
23 56 9 8 10 100
3 1 2
23 9 56 8 10 100
4 1 2
23 9 8 56 10
100
5 1 2
23 9 8 10 56 100
---- finish the first traversal ---1 1 2
23 9 8 10 56 100
2 1 2
9 23 8 10 56 100
3 1 2
9
8 23 10 56 100
4 1 2
9
8 10 23 56 100
---- finish the second traversal ---
1
Bubble Sort
public void bubbleSort (Comparable[] arr) {
boolean isSorted = false;
while (!isSorted) {
isSorted = true;
for (i = 0; i<arr.length-1; i++)
if (arr[i].compareTo(arr[i+1]) > 0) {
Comparable tmp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = tmp;
isSorted = false;
}
}
}
O Notation
O-notation Introduction
n = 2, tA(n) = 4 + 40 + 100
The constant, 100, is the dominating term
n = 10, tA(n) = 100 + 200 + 100
20n is the dominating term
n = 100, tA(n) = 10,000 + 2,000 + 100
n2 is the dominating term
n = 1000, tA(n) = 1,000,000 + 20,000 + 100
n2 is the dominating term
Big O Notation
Big O Notation
we write
4 * n 3n + 12 for all n 12
In English
O Notation Examples