ELEE28706D SortingAlgorithm S6
ELEE28706D SortingAlgorithm S6
Sorting: Definition
- Taking a list of objects which could be stored in a linear order (a0,
a1,….an-1)
- Returning and reordering (a`0, a`1,…a`n-1)
- Whereby, a`0 ≤ a`1… ≤ a`n-1)
- The objective is to rearrange the items such that their keys are in
ascending order (low to high)
Sorting: Problem
Sorting and Ordering
Step 1: Find the smallest element (5) and store in a[0] through
swapping with a[3]
Step 2: Find the minimum of the remaining entries, a[1] …a[4]
Sorting and Ordering
Selection Sort:
Step 3: Next minimum (9) is already in the correct place. Nothing to
swap. Simply extend the sorted area by one to the right.
Step 4: Repeat the process. The minimum value of the unsorted region
is 11, which needs to be swapped with the first value of the unsorted
region, 17
Sorting and Ordering
Selection Sort:
Step 5: Now, the unsorted region is only two elements long. The
minimum value is 12, and we swap it with the first value 17.
Insertion Sort:
Insertion Sort:
For example, consider this sorted array containing of eight sorted
entries
Suppose we want to insert 14 into this array leaving the resulting array
sorted
Sorting and Ordering
Insertion Sort:
Starting at the back, if the number is greater than 14, copy it to the right
Once an entry less than 14 is found, insert 14 into the resulting vacancy
Sorting and Ordering
• Exchange
• Selection
• Merging
• Distribution
- An Array where each entry is not far from its final position
- A small array appended to a larger sorted array
- An array with only a few entries that are not in place
- After one pass, the largest item must be the last in the
list
- Start at the front again
- The second pass will bring the second largest element
into the second last position
- Repeat n – 1 times, after which, all entries will be in
place
Sorting and Ordering
Here we have two nested loops, and therefore calculating the run
time is straight-forward:
n 1 n n 1 n n 1
k 1
n k n n 1
2
2
( n 2
)
Sorting and Ordering
Strategy:
- Given an unsorted list with n objects, place them into a
heap, and take them out.
Sorting and Ordering
n
n
k 1
ln( k ) ln
k 1
k ln n!
Two strategies:
– Assume 46 is a max-heap and keep inserting the next element into the
existing heap (similar to the strategy for insertion sort)
– Start from the back: note that all leaf nodes are already max heaps,
and then make corrections so that previous nodes also form max heaps
Sorting and Ordering
Starting with the next higher level, the subtree with root 48 can be
turned into a max-heap by swapping 48 and 99
Sorting and Ordering
h
k 0
2 k h k 2 h1 1 (h 1)
Sorting and Ordering
into a max-heap:
Sorting and Ordering
Repeat this process: pop the maximum element, and then insert it
at the end of the array:
Sorting and Ordering