简体   繁体   English

Python-当中间元素是pivot时如何实现快速排序?

[英]Python- How to implement quick sort when middle element is the pivot?

There are many different versions of quickSort that pick pivot in different ways.有许多不同版本的 quickSort 以不同的方式选择 pivot。

  • Always pick the first element or the last element as the pivot始终选择第一个元素或最后一个元素作为 pivot
  • Pick a random element as a pivot.选择一个随机元素作为 pivot。
  • Pick median as the pivot.选择中位数为 pivot。

I have implemented using the last element as the pivot everything worked fine but when I tried to implement the same logic to the middle element, it's no working fine.我已经使用the last element as the pivot一切正常,但是当我尝试对中间元素实现相同的逻辑时,它无法正常工作。

Here's my code in python:这是我在 python 中的代码:

import random
import time
start = time.time()

def quickSort(a,l,r):
    if(l<r):
        p = partition(a,l,r)
        quickSort(a,l,p-1)
        quickSort(a,p+1,r)

def partition(a,l,r):
    i = l-1
    p = a[(l+(r-l))//2]
    for j in range(l,r):
        if a[j] <= p:
            i += 1
            a[i],a[j] = a[j],a[i]
            
    a[i+1],a[r] = a[r],a[i+1]
    return (i+1)

N = 10
a = [random.randint(1,100) for i in range(N)]
print(a)
quickSort(a,0,N-1)
print(a)
print("It took %s milli seconds"%((time.time()-start)*100))

This is the output这是 output

[88, 35, 55, 68, 96, 23, 44, 77, 78, 71]
[35, 55, 23, 68, 44, 77, 88, 96, 78, 71]
It took 1.5625953674316406 milli seconds

Using Hoare partition scheme is better suited to using the middle value as pivot, and Hoare partition scheme is typically faster than the Lomuto partition scheme used in the question.使用 Hoare 分区方案更适合使用中间值作为 pivot,并且 Hoare 分区方案通常比问题中使用的 Lomuto 分区方案更快。

def qsort(a, lo, hi):
    if(lo >= hi):
        return
    p = a[(lo + hi) // 2]       # pivot, any a[] except a[hi]
    i = lo - 1
    j = hi + 1
    while(1):
        while(1):               # while(a[++i] < p)
            i += 1
            if(a[i] >= p):
                break
        while(1):               # while(a[--j] < p)
            j -= 1
            if(a[j] <= p):
                break
        if(i >= j):
            break
        a[i],a[j] = a[j],a[i]
    qsort(a, lo, j)
    qsort(a, j+1, hi)

As commented above, if you still want to use Lomuto partition scheme, swap the middle element with the last element and use your code with the last element.如上所述,如果您仍想使用 Lomuto 分区方案,请将中间元素与最后一个元素交换,并将您的代码与最后一个元素一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM