2016-07-11 45 views
-3
def PartitionDemo(a,p,r): 
    x=a[p] 
    start=p 
    end=r 
    while start<end : 
     while start<end and a[end]>=x : 
      end-=1 
     while start<end and a[start]<x : 
      a[start]=a[end] 
      start+=1 
      a[end]=a[start] 
    a[start]=x 
    return start 

def Partition2(a,low,high): 
    key = a[low] 
    while low < high: 
     while low < high and a[high] >= key: 
      high -= 1 
     while low < high and a[high] < key: 
      a[low] = a[high] 
      low += 1 
      a[high] = a[low] 
    a[low] = key 
    return low 

PartitionDemo我寫了自己,和Partition2我從互聯網上覆制它。但PartitionDemo不能正常運行;它不能跳出循環。他們使用相同的邏輯,我認爲,但Partition2運作良好。這兩個Quicksort分區函數有什麼區別?

我嘗試在C++,Java和Python中編寫Quicksort,但我不明白Python中發生了什麼問題。

+0

你這是什麼意思是當你說出來的時候「運行不正常?」請添加您的輸入,所需輸出和實際輸出(儘可能縮短以說明問題)。 – lwassink

+0

該程序沒有跳出循環,它什麼也不做 –

回答

1

的PartitionDemo有

while start<end and a[start]<x : 

其中分區2具有

while low < high and a[high] < key: 

,所以它看起來像你應該

while start<end and a[end]<x : 

與最終替換第二起始

+0

爲什麼它不同於C++邏輯?從最後找到更大的,從開始找到更小的? –

+0

什麼是C++代碼?我只是指出了兩個python函數之間的區別,他們如何不使用相同的邏輯。 – bltpyro