Week4: (Chapter 4) Sorting Techniques: Given Suppose Suppose Goal
Week4: (Chapter 4) Sorting Techniques: Given Suppose Suppose Goal
SORTING TECHNIQUES
– Start 1 23 2 56 9 8 10 100
– End 1 2 8 9 10 23 56 100
Week4: (Chapter 4)
SORTING TECHNIQUES
for(count=0;count<n-1;count++)
for(j=0;j<n-1-count;j++)
if(list[j] > list[j+1])
swap(list[j],list[j+1]);
} DEMO
2. Exchange Sorting
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(arr[i] > arr[j])
swap(arr[i],arr[j]);
} DEMO
2. Exchange Sorting
Notes:
– on each successive pass, do one less compare,
because the last item from that pass is in place
– if you ever make a pass in which no swap occurs,
the sort is complete
– There are some algorithms to improve
performance but Big O will remain O(n2)
3. Insertion Sort
3 7 5 2 4
take an item from the unsorted list (7) and
insert into the sorted list
sorted unsorted
3 7 5 2 4
take next item from the unsorted list (5) and
sorted unsorted insert into the sorted list
3 5 7 2 4
take next item from the unsorted list (2)
sorted unsorted and insert into the sorted list
2 3 5 7 4
take next item from the unsorted list (4)
sorted unsorted and insert into the sorted list
2 3 4 5 7
3. Insertion Sort
3 7 5 2 4
4. Selection Sort
3 4 5 2 7
biggest last
3 4 5 2 7
3 4 2 5 7
biggest last
3 4 2 5 7
3 2 4 5 7
3 2 4 5 7
2 3 4 5 7
4. Selection Sort
2) Divide: rearrange
elements so that x goes to its
final position E
Quick Sort
Pick the leftmost element as the pivot (23). Now , start two cursors (one at either end) going towards the middle
and swap values that are > pivot (found with left cursor) with values < pivot (found with right cursor)
23 17 5 12 19 24 4 43 34 11 3 33 14 26 8 27
swap
23 17 5 12 19 8 4 43 34 11 3 33 14 26 24 27
swap
23 17 5 12 19 8 4 14 34 11 3 33 43 26 24 27
swap
23 17 5 12 19 8 4 14 3 11 34 33 43 26 24 27
swap
Finally, swap the pivot and the value where the cursors passed each other
11 17 5 12 19 8 4 14 3 23 34 33 43 26 24 27
Note : 23 is now in the right place and everything to its left is < 23
and everything to its right is > 23
Quick Sort (worst case)
3 4 5 8 11 12 14 17 19 23 24 26 27 33 34 43
4 5 8 11 12 14 17 19 23 24 26 27 33 34 43
if (j > lower)
quickSort(Arr, lower, j);
if (i < upper)
quickSort(Arr, i, upper);
}