0% found this document useful (0 votes)
14 views8 pages

Working of Quick Sort

Uploaded by

Sake Anila
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views8 pages

Working of Quick Sort

Uploaded by

Sake Anila
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Working of Quick Sort

CS212 : Design & Analysis of Algorithms


Prof. Prateek Vishnoi

Indian Institute of Technology, Mandi


Steps of Quick Sort
• Select the last element of an array as a 𝑝𝑖𝑣𝑜𝑡 element.

• Initialise pointer 𝑗 as 1st(base address) index of an array.

• Initialise pointer 𝑖 which points to the address just before the base address of an array.

• Iterate the pointer 𝑗 over an array with the following conditions:


 If the value at pointer 𝑗 is ≥ 𝑝𝑖𝑣𝑜𝑡, IGNORE.
 If value at pointer 𝑗 < 𝑝𝑖𝑣𝑜𝑡, then 𝑖++ and swap(value at 𝑖 , value at 𝑗)
 Recursively call the Quick Sort Function on a left subarray of the 𝑝𝑖𝑣𝑜𝑡 element.
 Recursively call the Quick Sort Function on a right subarray of the 𝑝𝑖𝑣𝑜𝑡 element.

Indian Institute of Technology, Mandi


𝑖 �

9𝑝𝑖𝑣𝑜𝑡

8 2 4 7 1 3
=5
𝑣𝑎𝑙(𝑗) > 𝑝𝑖𝑣𝑜𝑡,
6 5
𝑖 𝑗
𝐼𝐺𝑁𝑂𝑅𝐸, 𝑗++

8 2 4 7 1 3 9
6 5 𝑣𝑎𝑙(𝑗) < 𝑝𝑖𝑣𝑜𝑡, 𝑖++ ,
𝑖
𝑠𝑤𝑎𝑝(𝑣𝑎𝑙(𝑖), 𝑣𝑎𝑙(𝑗))


2 8 4 7 1 3 9
𝑗+
6 5
𝑖 � +

2 8 4 7 1 3 9
6 5
Indian Institute of Technology, Mandi
𝑖 �

2 8 4 7 1 3 9
6 5
𝑣𝑎𝑙(𝑗) < 𝑝𝑖𝑣𝑜𝑡, 𝑖++ ,
𝑖
𝑠𝑤𝑎𝑝(𝑣𝑎𝑙(𝑖), 𝑣𝑎𝑙(𝑗))


2 4 8 7 1 3 9
𝑗+
6 5
𝑖 �
+

2 4 8 7 1 3 9
6 5 𝑣𝑎𝑙(𝑗) > 𝑝𝑖𝑣𝑜𝑡,
𝑖 𝐼𝐺𝑁𝑂𝑅𝐸
� , 𝑗++

2 4 8 7 1 3 9
6 5
Indian Institute of Technology, Mandi
𝑖 �

2 4 8 7 1 3 9
6 5 𝑣𝑎𝑙(𝑗) < 𝑝𝑖𝑣𝑜𝑡, 𝑖++ ,
𝑖 𝑠𝑤𝑎𝑝
� (𝑣𝑎𝑙(𝑖), 𝑣𝑎𝑙(𝑗))

2 4 1 7 8 3 9
6 5 𝑗+
𝑖 �
+

2 4 1 7 8 3 9
6 5 𝑣𝑎𝑙(𝑗) < 𝑝𝑖𝑣𝑜𝑡, 𝑖++ ,
𝑖 𝑠𝑤𝑎𝑝(𝑣𝑎𝑙 �(𝑖), 𝑣𝑎𝑙(𝑗))

2 4 1 3 8 7 9
6 5

Indian Institute of Technology, Mandi


𝑖 �

2 4 1 3 8 7 9
6 5 𝑣𝑎𝑙(𝑗) > 𝑝𝑖𝑣𝑜𝑡,
𝑖 𝐼𝐺𝑁𝑂𝑅𝐸, 𝑗++�

2 4 1 3 8 7 9
6 5 𝑣𝑎𝑙(𝑗) > 𝑝𝑖𝑣𝑜𝑡,
𝑖 𝐼𝐺𝑁𝑂𝑅𝐸, 𝑗++ �

2 4 1 3 8 7 9
6 5 𝑣𝑎𝑙(𝑗) > 𝑝𝑖𝑣𝑜𝑡,
𝑖 𝐼𝐺𝑁𝑂𝑅𝐸, 𝑗++ �

2 4 1 3 8 7 9
6 5
Indian Institute of Technology, Mandi
𝑖 �

2 4 1 3 8 7 9
6 5 𝑗 pointing to pivot, 𝑖++, swap(value(𝑖), pivot)

2 4 1 3 5 7 9
6 8
𝑖 �

𝑝𝑖𝑣𝑜𝑡

2 4 =3
7 9 6
1 3 8
𝑖 𝑣𝑎𝑙(𝑗) < 𝑝𝑖𝑣𝑜𝑡, 𝑖++ ,
𝑠𝑤𝑎𝑝(𝑣𝑎𝑙(𝑖), 𝑣𝑎𝑙(𝑗))


2 4
1 3
Indian Institute of Technology, Mandi
2 4 1 3 5 7 9
6 8
𝑖 � 𝑖 �

𝑝𝑖𝑣𝑜𝑡 𝑝𝑖𝑣𝑜𝑡
� �
2 4 1 =3
7 9 6 =8
3 𝑣𝑎𝑙(𝑗) < 𝑝𝑖𝑣𝑜𝑡, 𝑖++ , 8 𝑣𝑎𝑙(𝑗) < 𝑝𝑖𝑣𝑜𝑡, 𝑖++ ,
𝑖 � 𝑠𝑤𝑎𝑝(𝑣𝑎𝑙(𝑖), 𝑣𝑎𝑙(𝑗)) 𝑖 � 𝑠𝑤𝑎𝑝(𝑣𝑎𝑙(𝑖), 𝑣𝑎𝑙(𝑗))
� �
2 4 7 9 6
1 3 𝑗+
8 𝑗+
𝑖 � 𝑖 �
+
+
� �
2 4 1 7 9 6
3 8
Follow the same Follow the same
steps steps
Indian Institute of Technology, Mandi

You might also like