Sorting Algorithms: Merge Sort and Quick Sort, Slides of Data Structures and Algorithms

An overview of merge sort and quick sort, two popular comparison-based sorting algorithms. Learn about their working principles, advantages, and disadvantages.

Typology: Slides

2012/2013

Uploaded on 04/23/2013

saratey
saratey 🇮🇳

4.3

(10)

86 documents

1 / 32

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20

Partial preview of the text

Download Sorting Algorithms: Merge Sort and Quick Sort and more Slides Data Structures and Algorithms in PDF only on Docsity!

Merge Sort

Merging Two Sorted Arrays

All the work in merge sort is done at the merge step.

Example

1

13

24

26

2

15

27

38

Quick Sort

Quicksort idea



Choose a pivot.



Rearrange so thatpivot is in the “right”spot.



Recurse on each halfand conquer!

Quicksort algorithm

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

Place the pivot algorithm



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);

Example

Show how to place the pivot (choose middle element)in the right place

34 24 56 17 19 45 90 23 36

Naïve sorting algorithms



Bubble sort:

scan for flips, until all are fixed

Etc...

Naïve Sorting

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?

of slides = O(#inversions)

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

Advanced Sorting