2014-10-31 42 views
0

我已經使用Sedgewick在課程中教授的算法在Python中編寫了Quicksort的實現。我無法正確分類。代碼有什麼問題?無法實現Quicksort

def partition(a, lo, hi): 
    i = lo 
    j = hi 
    v = a[lo] 
    while(True): 
     while(a[i] < v): 
      i += 1 
      if (i == hi): break 

     while(a[j] > v): 
      j -= 1 
      if (j == lo): break 

     if (i >= j): break 

     a[i], a[j] = a[j], a[i] 

    a[lo], a[j] = a[j], a[lo] 
    return j 

def sort(a, lo, hi): 
    if (hi <= lo): 
     return 
    q = partition(a, lo, hi) 
    sort(a, lo, q-1) 
    sort(a, q+1, hi) 
    assert isSorted(a, lo, hi) 

def quick_sort(a): 
    shuffle(a) 
    sort(a, 0, len(a)-1) 
    assert isSortedArray(a) 
+0

此外,你缺乏運氣在選擇StackExchange社區問問,如果沒有別的。 (您如何對單個快速排序實現進行排序?) – greybeard 2015-02-16 23:57:06

回答

0

你可能會發現這些參考實現有助於理解你自己。


返回一個新的列表:

def qsort(array): 
    if len(array) < 2: 
     return array 
    head, *tail = array 
    less = qsort([i for i in tail if i < head]) 
    more = qsort([i for i in tail if i >= head]) 
    return less + [head] + more 

排序到位的列表:

def quicksort(array): 
    _quicksort(array, 0, len(array) - 1) 

def _quicksort(array, start, stop): 
    if stop - start > 0: 
     pivot, left, right = array[start], start, stop 
     while left <= right: 
      while array[left] < pivot: 
       left += 1 
      while array[right] > pivot: 
       right -= 1 
      if left <= right: 
       array[left], array[right] = array[right], array[left] 
       left += 1 
       right -= 1 
     _quicksort(array, start, right) 
     _quicksort(array, left, stop) 

生成排序從一個可迭代的項目:

def qsort(sequence): 
    iterator = iter(sequence) 
    head = next(iterator) 
    try: 
     tail, more = chain(next(iterator), iterator), [] 
     yield from qsort(split(head, tail, more)) 
     yield head 
     yield from qsort(more) 
    except StopIteration: 
     yield head 

def chain(head, iterator): 
    yield head 
    yield from iterator 

def split(head, tail, more): 
    for item in tail: 
     if item < head: 
      yield item 
     else: 
      more.append(item) 
+0

請鏈接到您在答案中找到參考實現的位置。 – 2014-10-31 14:20:34

+0

我編寫了參考實現,但是在StackOverflow中至少可以找到一個其他答案,他們最初在對其他實現存在不滿意之後發佈到Rosetta Code。 – 2014-10-31 14:24:39