Often it useful to talk about measures of list sortedness. Such a
distance measure should assign a score of zero to a sorted
list, and any unsorted list should score a positive amount.
Some measures:
- Unsortedp: Is the list completely sorted? Score 1 if no.
- Items out of place: Score 1 for each position that contains an
element other than what would be there in a sorted list. Maximum
distance is n.
- Inversions: Score 1 for every pair that is out of order. Maximum
distance is n(n-1)/2.
- Adjacent inversions: Score 1 for every adjacent pair that is out
of order. Maximum distance is n-1.
- Insertion index: Find the longest increasing subsequence (LIS).
Score n minus the length of the LIS. The same as asking, what's the
smallest number of keys I can remove and the reinsert to get a sorted
list? Maximum distance is n-1.
Example:
- 2 1 6 3 5 4 7
- unsortedp: 1
- items out of place: 5.
- inversions: 1+0+3+0+1=5.
- adjacent inversions: 3.
- insertion index: 7-4=3.
Next: Sorting with Small Insertion
Up: INSERTION SORT
Previous: Step 3: Efficiency