Question

Is quick sort a stable or unstable sorting algorithm. Explain with an example.

Is quick sort a stable or unstable sorting algorithm. Explain with an example.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Quick Sort is an Unstable sorting algorithm

Proof:

Stable Sorting algorithm is that maintains the relative position of element after sorting i.e. if we have following elements 1,9 8,8,9,2,4,5, we can represent as

a-1,b-9, c-8,d-8,e-9,f-2,g-4,h-5 the sorting order will be 1,2,4,5,8,8,9,9 which is clearly explained in the picture.

Before Sorting a b c d e f g h 1988 92 45 Stable Sorting afgnc del 112458899 Unstable Sorting afghd Ceb 1245 88 99

In the Stable sort elemets will be sorted and it also maintains order, in this example we can see 8 comes two times which is in the position c & d. In the stable sort the c comes before d even though the elements are same, Whereas in the Unstable sort order is not maintained, i.e., d comes before c.

why quick sort is unstable sorting ?

Let us take example 1,9 8,8,9,2,4,5 now we have to sort using quick sort.

first we will consider the pivotal element is last element i.e. 5

pivot=a[end]

now two indices i=start-1; j=start i.e. i=-1 and j=0 now from left of array keep seeing element if it is less then pivot i.e. 5 swap with left most element index by i and finally place the pivot element at position where all the element left to pivot is less then pivot and right greater. Now start

1,9 8,8,9,2,4,5

1<5 so swapping i=0,j=1

next 9,8,8,9 are not less 5 so no swapping so j will be 4. now next 2 <5 so swapping so not

1,2,8,8,9,9,4,5 i=1 and j=5 so now the 9 was before is swapped after 9 which was relative behind of first 9 so unstable again 4<5 so swapping 1,2,4,8,9,8,9,8,5

finally swap the pivot with i=3 so 1,2,4,5,8,9,8,9.

now see 8 and 9 are swapped with the later 8,9 which is relative order has changed.

Since the relative order is not followed, we can say that quick sort is UNSTABLE SORTING ALGORITHM

Add a comment
Know the answer?
Add Answer to:
Is quick sort a stable or unstable sorting algorithm. Explain with an example.
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT