这个快排哪儿有问题?

#coding=utf-8
import random ls = [random.randint1,20 for i in range30] def quick_sortli: if lenli <=10: li.sort return li lenth = lenli if li[0]>li[lenth / 2]: li[lenth / 2], li[0] = li[0], li[lenth / 2] if li[0] > li[lenth-1]: li[lenth-1], li[0] = li[0], li[lenth-1] if li[lenth/2]>li[lenth-1]: li[lenth-1], li[lenth/2] = li[lenth/2], li[lenth-1] li[lenth/2], li[lenth-1] = li[lenth-1], li[lenth/2] i,j = 0 ,lenth-2 while 1: while li[i]<=li[lenth-1] and i<lenth-2: i = i+1 while li[j] > li[lenth-1] and j >= i: j = j-1 if i>=j: break else: li[i], li[j] = li[j], li[i] li[i+1], li[lenth-1] = li[lenth-1], li[i+1] li = quick_sortli[:i] + quick_sortli[i:] return li if __name__ == __main__: print quick_sortls

二分排序,给你php版的,你用python照着改:

二分排序:
function quickSort$left,$right,$arr{ $l=$left; $r=$right; $pivot=$arr[$left+$right/2]; while$l<$r{ while $arr[$l]<$pivot $l++; while $arr[$r]>$pivot $r++; if$l>=$r break; $temp=$arr[$l]; $arr[$l]=$arr[$r]; $arr[$r]=$temp; if$arr[$l]==$pivot --$r; if$arr[$r]==$pivot ++$l; } if$l==$r{ $l++; $r--; } if$left<$r quickSort$left,$r,$arr; if$right>$i quickSort$l, $right, $arr; return $arr;
}
$arr=array0,5,-1,20,-20,45,32,-100,-200;
$test=quickSort0,count$arr-1,$arr;
print_r$test;

我不是很喜欢可以用递归的强行用while循环来写,要换成循环就干脆换成迭代的。
英文必应搜索quick sort python给的样例:

#Quick Sort
def quicksortarr,i,j: if i<j: pos=partitionarr,i,j quicksortarr,i,pos-1 quicksortarr,pos+1,j def partitionarr,i,j: pivot=arr[j] small=i-1 for k in rangei,j: if arr[k]<=pivot: small+=1 swaparr,k,small swaparr,j,small+1 print "Pivot= "+strarr[small+1] print arr return small+1
def swaparr,i,j: temp=arr[i] arr[i]=arr[j] arr[j]=temp arr=[9,4,8,3,1,2,5]
print "Initial Array :"+strarr quicksortarr,0,lenarr-1 

发表评论

电子邮件地址不会被公开。 必填项已用*标注