Stability of quicksort partitioning approach

后端 未结 8 2078
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 01:12

Does the following Quicksort partitioning algorithm result in a stable sort (i.e. does it maintain the relative position of elements with equal values):

  pa         


        
8条回答
  •  误落风尘
    2020-12-05 01:33

    A sort is stable when the original order of similar elements doesn't change. Your algorithm isn't stable since it swaps equal elements.

    If it didn't, then it still wouldn't be stable:

    ( 1, 5, 2, 5, 3 )
    

    You have two elements with the sort key "5". If you compare element #2 (5) and #5 (3) for some reason, then the 5 would be swapped with 3, thereby violating the contract of a stable sort. This means that carefully choosing the pivot element doesn't help, you must also make sure that the copying of elements between the partitions never swaps the original order.

提交回复
热议问题