Sorting and Searching
Sorting and Searching
Searching
Searching
Given a list of data find the location of a
particular value or report that value is not
present
linear search
intuitive approach
start at first item
is it the one I am looking for?
if not go to next item
repeat until found or all items checked
/*
Linear Search
*/
int linearSearch(int list [], int target, int length)
BEGIN
FOR i = 0 TO i<length STEP 1
IF( list[i] == target )
return i;
ENDIF
ENDFOR
return -1;
END
Binary Search
list
low item
middle item
high item
Is middle item what we are looking for? If not is it
more or less than the target item? (Assume lower)
list
low
item
middle
item
high
item
and so forth
Sorting and Searching
11 13 17 19 23 29 31 37 41 43 47 53
return result;
}
// mid = ( low + high ) / 2; // may overflow!!!
// or mid = (low + high) >>> 1; using bitwise op
Sorting and Searching
Indexed Searching
Binary Search Trees
Hash Table Searching
Grover's Algorithm (Waiting for
quantum computers to be built)
best-first
A*
Sorting and Searching
10
Sorting
11
Sorting
12
Sorting
A fundamental application for computers
Done to make finding data (searching) faster
Many different algorithms for sorting
One of the difficulties with sorting is working
with a fixed size storage container (array)
if resize, that is expensive (slow)
13
Stable Sorting
A property of sorts
If a sort guarantees the relative order of
equal items stays the same then it is a stable
sort
[71, 6, 72, 5, 1, 2, 73, -5]
subscripts added for clarity
14
Algorithm
Selection sort
15
16
Insertion Sort
The first item is sorted
Compare the second item to the first
if smaller swap
And so forth
17
18
19
Comparing Algorithms
Which algorithm do you think will be faster
given random data, selection sort or insertion
sort?
Why?
20
Selection
Insertion
Shellsort
Quicksort
1000
16
2000
59
49
4000
271
175
8000
1056
686
11
10
16000
4203
2754
32
11
32000
16852
11039
37
45
64000
expected?
expected?
100
68
128000
expected?
expected?
257
158
256000
expected?
expected?
543
335
512000
expected?
expected?
1210
722
1024000
expected?
expected?
2522
1550
times in milliseconds
Sorting and Searching
21