Stable sort talks about equal keys NOT getting past each other, after sorting
Consider duplicate key 4 at array index 8 & 9, in the below sequence,
a= [5 20 19 18 17 8 4 5 4 4] wherepivot= 0,i= 1,j= 9Partition logic says,
ipointer moves left to right. Moveias long asa[i]value is ≤ toa[pivot].swap(a[i], a[j])
jpointer moves right to left. Movejas long asa[j]value is ≥ toa[pivot].swap(a[i], a[j])
After following this procedure two times,
a= [5 4 19 18 17 8 4 5 4 20] Swap done ati= 1 &j= 9.
a= [5 4 19 18 17 8 4 5 4 20] Stops ati= 2 &j= 8
a= [5 4 4 18 17 8 4 5 19 20] Swap done ati= 2 &j= 8
My understanding is, as duplicate key 4 lost their order after two swaps, Quick sort is not stable sort.
Question:
As per my understanding, Is this the reason for Quick sort not being stable? If yes, Do we have any alternative partition approach to maintain the order of key 4 in the above example?