Sorting
Sorting
Sorting
Sorting
Selection Sort
Select the largest element in your array and
swap it with the first element of the array.
Consider the sub-array from the second
element to the last, as your current array and
repeat Step 1.
Stop when the array has only one element.
main() {
arr[] = { 5, 6, 2, 3, 1, 4 };
selection_sort(arr, 0, 5);
/* print arr */
}
4
Selection Sort
What is the estimated run time
when input array has n elements
Constant
for swap
for find_idx_of_max_elt
?
for selection_sort
At each iteration
Time Estimate
Merge Sort
Recursive calls.
Base case?
n <= 1
10
}
11
Time Estimate
void merge_sort(int a[], int s, int n) {
if (n>1) {
int h = n/2;
merge_sort(a, s, h);
merge_sort(a, s+h, n-h);
merge(a, s, n);
}
}
Time Estimates
Why worry
about O(n) vs
O(n2) vs O()
algorithm?
http://xkcd.com/612/
14
SelectionSort
MergeSort
Simple Search
BinSearch
Source: http://science.slc.edu/~jmarshall/courses/2002/spring/cs50/BigO/
Time Estimates
15
10
35
59
31
25
35
11
31
59
35
35
31
10
11
left partition
25
right partition
18
Observations
19
20
a
31
Designing Partition
4
10
35
59
31
31
25
35
11
10
pivot
r
l
1. Keep two integer variables denoting indices: l starts at the left
end and r starts at the right end.
2. pivot is a[0] which is 31.
3. Value of pivot will not change during partition.
Basic Step in Partition Loop:
As long as a[l] < pivot, increment l by 1.
As long as a[r] > pivot, decrease r by 1.
If l < r, Exchange a[l] with a[r].
advance l by 1; decrement r by 1
21
a
31
Designing Partition
4
10
35
59
31
31
10
pivot
25
35
11
22
a
0
Designing Partition
4
10
35
59
31
31
pivot
25
35
11
31
23
a
0
Designing Partition
4
10
35
59
31
31
pivot
25
35
11
31
24
a
0
Designing Partition
4
10
11
59
31
31
pivot
25
35
35
31
25
a
0
Designing Partition
4
10
11
59
31
31
pivot
25
35
35
31
26
a
0
Designing Partition
4
10
11
25
31
31
pivot
59
35
35
31
27
a
0
Designing Partition
4
10
11
25
31
31
pivot
59
35
35
31
28
a
0
Designing Partition
4
10
11
25
31
31
pivot
59
35
35
31
29
30
Pivoting choices
Pivot may be chosen to be any value of a[]. Some choices are
1. Pivot is a[0]: simple choice.
2. Pivot is some random member of a[]: randomized pivot
choice.
3. Pivot is the median element of a[]. This gives the most
equal sized partitions, but is much more complicated.
Sorting
After the call pindex = partition(a,start,end)
1. each element of a[start,,pindex] <= pivot.
2. each element of a[pindex+1,,end] >= pivot.
Suppose we wish to sort the array a[].
To sort a[], we can sort the left partition and the right partition
independently.
QuickSort
void qsort(int a[], int start, int end) {
int pindex;
if (start >=end) return; /* nothing to sort */
else {
pindex = partition(a, start, end);
qsort(a, start, pindex);
qsort(a, pindex+1, end);
}
}