Searching2409

advertisement
Sorting: putting items in order according to
some criterion
Ascending numeric, descending numeric, could
be string-based like sort records on last name,
if same, first name, if same ssn
Expensive operation: takes a lot of computation
Better sorts (still bad) and worse sorts: less
complicated
Bubble, selection, insertion are the worse sorts
Better sorts are mergesort, quicksort, shellsort
Base selection on imagined order of data
We’re going to look at the worse sorts: all inplace sorts (move around within same array)
With sorts and searches, keep correct idea of
when to use index versus when to use value
Compare values, generally store indices
All in common:
60 40 20 50 30 5 pieces of data
Have to make several sequential passes over
the data
After a pass, one more is guaranteed in the
right place
20 __ __ __ __
20 30 __ __ __
20 30 40 __ __
20 30 40 50 ?_
For N elements, N – 1 passes over the data
Nested loop, outer controls passes, inner
controls comparisons and data movement
within a pass
Have sorted and unsorted area
Each pass, sorted grows by 1
Pass number is item that will be sorted after
the pass
Bubble and selection:
Passes 0 to N – 2
Moving items around in unsorted area
Assume empty sorted area
Insertion:
Passes 1 to N – 1
Assume 0th in place (which it is for existing
sorted area)
Moving items around in sorted area
Bubble and selection differ with what happens
within a pass
Bubble: pass and trav: ascending numeric
pass is position to be sorted, trav starts at end
and compares its value with value at one less
swaps if necessary
n1 = n2;
n2 = n1; // doesn’t work, need temporary
third
temp = n1;
n1 = n2;
n2 = temp;
3 assignments per swap
60 40 20 50 30
60 40 20 30 50
60 40 20 30 50
60 20 40 30 50
20 60 40 30 50
20 |
20 |
60 40 30 50
60 40 30 50
20 |
60 30 40 50
20 |
30 60 40 50
20 30 |
60 40 50
20 30 |
60 40 50
20 30 |
40 60 50
20 30 40 |
20 30 40 |
60 50
50 60
set pass to 0 // ascending numeric
while have more passes (pass <= N – 2)
set trav to N – 1
while trav > pass (not yet to front of unsorted area)
if value at trav is < value at trav – 1 // > for descending
swap
end if
decrement trav
end while
increment pass
end while
If get through a pass, and there are no swaps, will
be none the next time, in order, count swaps and
add to condition to shortcut number of passes if
sorted ahead of time
Download