0% found this document useful (0 votes)
12 views

Quick Sort

Uploaded by

samarth
Copyright
© © All Rights Reserved
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Quick Sort

Uploaded by

samarth
Copyright
© © All Rights Reserved
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Quick Sort

Example
Consider the list: 42, 23, 74, 11, 65, 58,
94, 36, 99, 87
Take 42 as pivot element.

42 23 74 11 65 58 94 36 99 87

key 74>42 ,
23>42 ,
Yes
No.
Store the
Go to next
location, it is
element
3.
Search for
bigger
element than
key from left
to right. Stop
when found.
Example
Consider the list: 42, 23, 74, 11, 65, 58,
94, 36, 99, 87

42 23 74 11 65 58 94 36 99 87

key 87<42 , 99<42 ,


No. No.
Go to Go to
previous previous
Search for element 36<42 ,
element.
smaller Yes
element than Store the
key from right location, it is
to left. Stop 8.
when found.
Example
Consider the list: 42, 23, 74, 11, 65, 58,
94, 36, 99, 87
Exchange K[3] and K[8]. New list will be:

42 23 36 11 65 58 94 74 99 87

key

Repeat procedure again. With left position start with 4


and right position for 7.

You will note that bigger element than 42 is 65( at


position 5) and smaller element is 11(at position 4)

Here these two pointers crosses each other. So at that


time smaller element is replaced by Key element or
pivot element.
Example
Consider the list: 42, 23, 74, 11, 65, 58,
94, 36, 99, 87
New list will be:

11 23 36 42 65 58 94 74 99 87

Larger than
key Smaller than
pivot pivot
Any observation here?

Observe the elements at left and right of the pivot


element.
Example
Consider the list: 42, 23, 74, 11, 65, 58,
94, 36, 99, 87
New list will be:

11 23 36 42 65 58 94 74 99 87

Now 42 is at its right position.

Two parts are created of the list. Both needs to be


sorted using the same method.

What are the function calls? What can be the arguments?


Algorithm: QUICK_SORT(K,LB,UB)
1.[Initialize] Repeat while
flag<- true K[j]>key
If i<j j=j-1
2.[Perform Sort] then k[i]<->k[j]
if LB<UB else flag=false
then i=LB
j=UB+1 k[LB]<->k[j]
key=K[LB]
Call QUICK_SORT(K,LB,j-1)
Repeat while flag
Call QUICK_SORT(K,j+1,UB)
i=i+1
Repeat while 3. Finished
K[i]<key
i=i+1
j=j-1

You might also like