sorting and searching
sorting and searching
11 9 17 5 12
Sorting an Array of Integers
1. Find the smallest and swap it with the first element
5 9 17 11 12
5 9 11 17 12
4. Repeat
5 9 11 12 17
10,000 786
20,000 2,148
30,000 4,796
40,000 9,192
50,000 13,321
Figure 1 Time Taken by Selection Sort
60,000 19,299
Doubling the size of the array more than doubles the time
needed to sort it.
The curve resembles a parabola.
Analyzing the Performance of
the Selection Sort Algorithm
In an array of size n, count how many times an array
element is visited:
To find the smallest, visit n elements + 2 visits for the swap
To find the next smallest, visit (n - 1) elements + 2 visits for
the swap
The last term is 2 elements visited to find the smallest + 2
visits for the swap
Analyzing the Performance of
the Selection Sort Algorithm
The number of visits:
n + 2 + (n - 1) + 2 + (n - 2) + 2 + . . .+ 2 + 2
This can be simplified to n2 /2 + 5n/2 - 3
5n/2 - 3 is small compared to n2 /2 when n gets large – so let's ignore it
Also ignore the 1/2 – it cancels out when comparing ratios
Analyzing the Performance of
the Selection Sort Algorithm
11 9 16 5 7
9 11 16 5 7
§ Add a[2]
9 11 16 5 7
§ Add a[3]
5 9 11 16 7
§ Sorts an array by
§ Cutting the array in half
§ Recursively sorting each half
§ Merging the sorted halves
20,000 73 2,148
§ The last value of the first half of this very short sequence is
12,
This is smaller than the value that we are searching, so we
must look in the second half
Assume n is a power of 2, n = 2m
where m = log2(n)
For example
int[] a = { 1, 4, 9 };
int v = 7;
int pos = Arrays.binarySearch(a, v);
// Returns –3; v should be inserted before position 2
Comparing Objects
Arrays.sort sorts objects of classes that
implement Comparable interface:
public interface Comparable<T>
{
int compareTo(T other);
}