Lel*_*uch 1 python sorting algorithm
我写的递归一个简单的分类代码,我测试它Python 2.7.6和Python 3.3.3.但我得到了两个不同的结果.代码如下.
import math, copy, random, sys
call_count = 0; # Keep track of number of times of stooge_sort() get called
swap_count = 0; # Keep track of number of times swapping.
def stooge_sort(a, origin):
global call_count, swap_count;
call_count += 1;
n = len(a);
m = int(math.ceil(n*2/3));
if(n == 2 and a[0] > a[1]):
a[0], a[1] = a[1], a[0];
swap_count += 1;
elif (n > 2):
first = copy.deepcopy(a[0:m]);
a[0:m] = stooge_sort(first, origin);
second = copy.deepcopy(a[n-m:]);
a[n-m:] = stooge_sort(second, origin);
first = copy.deepcopy(a[0:m]);
a[0:m] = stooge_sort(first, origin);
return a;
a = [int(random.random() * 100) for i in range(10)];
stooge_sort(a, a);
print("sort function call count = " + str(call_count))
print("swap count = " + str(swap_count));
Run Code Online (Sandbox Code Playgroud)
1)如果我跑进来Python 2.7.6,我会得到错误的排序和
sort function call count = 40
swap count = 2
Run Code Online (Sandbox Code Playgroud)
2)如果我跑进来Python 3.3.3,我得到正确的排序和
sort function call count = 364
swap count = 18
Run Code Online (Sandbox Code Playgroud)
所以我想知道哪个部分出了问题Python 2.7.6?
这完全是因为这条线
m = int(math.ceil(n*2/3));
Run Code Online (Sandbox Code Playgroud)
在Python 2中,n*2/3给出一个比实际值小1的值,因为浮点值被截断(因为/在Python 2.x中进行了分区),但是在Python 3中,它将进行适当的浮点除法.
要使程序表现一致,只需确保使用浮点数
m = int(math.ceil(n*2.0/3.0))
Run Code Online (Sandbox Code Playgroud)