
























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An overview of merge sort and quick sort, two popular comparison-based sorting algorithms. Learn about their working principles, advantages, and disadvantages.
Typology: Slides
1 / 32
This page cannot be seen from the preview
Don't miss anything!

























All the work in merge sort is done at the merge step.
Example
1
13
24
26
2
15
27
38
Quicksort idea
Choose a pivot.
Rearrange so thatpivot is in the “right”spot.
Recurse on each halfand conquer!
If array A has 1 (or 0) elements, then done.
Choose a
pivot element
x from A.
Divide A-{x} into two arrays:
B = {y
A | y≤x}
C = {y
A | y
x}
Result is B+{x}+C.
Recurse on arrays B and C
Assume we have an array of size n
Pick a pivot x
Place the pivot x in the last place of the array
Have two pointers i = 0, j = n- while ( i <= j) {
while (A[j] > pivot) j--;while (A[i] < pivot) i--;swap (A[i], A[j]); } swap (A[i], pivot);
Show how to place the pivot (choose middle element)in the right place
34 24 56 17 19 45 90 23 36
Bubble sort:
scan for flips, until all are fixed
Etc...
for i=1 to n-
{ for j=0 to n-i-
if (A[j].compareTo(A[j+1])>0)
swap(A[j], A[j+1]);
if (no swaps) break; }
What happens if
All keys are equal?
Keys are sorted in reverse order?
Keys are sorted?
keys are randomly distributed?
Exercise: Count the number of operations in bubble sortand find a Big O analysis for bubble sort
Insertion sort^ •
Algorithm for
i =
1
to
n-
do
insert a[i] in the proper place
in
a[0:i-1]
Correctness
•Note: after i steps, the sub-array A[0:i] issorted
How fast is insertion sort?
very fast if array is nearly sorted to begin with
tmp
a[i];
for
(j = i;
j>0 && a[j-1]>tmp; j--)
a[j] = a[j-1];
a[j]
= tmp;
To insert a[i] into a[0:i-1],
slide
all elements larger
than a[i] to the right.
Sorting Comparison
Discuss the pros and cons of each of the naïve sortingalgorithms