def test_randomized_quicksort(self): for i in range(100): A = [random.randint(1, 10000) for i in range(100)] B = A[:] randomized_quicksort(A, 0, len(A) - 1) B.sort() self.assertEqual(A, B)
def test_randomized_quicksort(self): for i in range(0, 100): A = [random.randint(1, 10000) for i in range(0, 100)] B = A[:] randomized_quicksort(A, 0, len(A) - 1) B.sort() self.assertEquals(A, B)
def note(self): ''' Summary ==== Print chapter7.3 note Example ==== >>> Chapter7_3().note() ''' print('chapter7.3 note as follow') print('7.3 快速排序的随机化版本') print('在探讨快速排序的平均性态过程中,假定输入数据的所有排列都是等可能的') print('但在工程中,这个假设就不会总是成立') print('虽然第五章介绍过一些随机算法,但是如果采用一种不同的,称为随机取样的随机化技术的话,可以使分析更加简单') print('在这种方法中,不是时钟采用A[r]作为主元,而是从子数组A[p..r]中随机选择一个元素') print('然后将这个随机元素与A[r]交换作为主元') print('因为主元元素是随机选择的,在期望的平均情况下,对输入数组的划分比较对称') A = [8, 7, 6, 5, 4, 3, 2, 1] print('数组[8, 7, 6, 5, 4, 3, 2, 1]的随机化快速排序:', quicksort.randomized_quicksort(A)) print( '练习7.3-1:大部分时候输入的待排序序列我们是不知道的,而对于快速排序来讲,一个平均的输入才能反映其算法性能,最坏情况出现的概率比较小' ) print('练习7.3-2:最佳情况调用Θ(n)次,最坏情况调用Θ(n^2)次')
def median_of_two_arrays(X, x_start, x_end, Y, y_start, y_end, size): print X[x_start:x_end + 1], '\t', Y[y_start:y_end + 1], '\t', size if size == 1: return min(X[x_start], Y[y_start]) xc = X[x_start + int(math.floor(size / 2)) - 1] yc = Y[y_start + int(math.ceil(size / 2)) - 1] print xc, yc if xc == yc: return xc elif xc < yc: return median_of_two_arrays(X, x_start + int(math.floor(size / 2)), x_end, Y, y_start, y_end, math.ceil(size / 2)) else: return median_of_two_arrays(X, x_start, x_end, Y, y_start + int(math.ceil(size / 2)), y_end, math.floor(size / 2)) A = [random.randint(1, 100) for i in range(0, 15)] print A randomized_quicksort(A, 0, 14) print A B = [random.randint(1, 100) for i in range(0, 15)] print B randomized_quicksort(B, 0, 14) print B print median_of_two_arrays(A, 0, 14, B, 0, 14, 3.0) #randomized_select(A, 0, 14, 7) #print A #for i in range(1, 16): # randomized_select(A, 0, 14, i) # print i, '\t', A # print randomized_select(A, 0, 14, i)
def test_randomized_quicksort(self): a = [3, 2, 4, 1, 5, 6] qs.randomized_quicksort(a, 0, len(a) - 1) b = [1, 2, 3, 4, 5, 6] self.assertEqual(a, b)
xc = X[x_start + int(math.floor(size / 2)) - 1] yc = Y[y_start + int(math.ceil(size / 2)) - 1] print xc, yc if xc == yc: return xc elif xc < yc: return median_of_two_arrays(X, x_start + int(math.floor(size / 2)), x_end, Y, y_start, y_end, math.ceil(size / 2)) else: return median_of_two_arrays(X, x_start, x_end, Y, y_start + int(math.ceil(size / 2)), y_end, math.floor(size / 2)) A = [random.randint(1, 100) for i in range(0, 15)] print A randomized_quicksort(A, 0, 14) print A B = [random.randint(1, 100) for i in range(0, 15)] print B randomized_quicksort(B, 0, 14) print B print median_of_two_arrays(A, 0, 14, B, 0, 14, 3.0) #randomized_select(A, 0, 14, 7) #print A #for i in range(1, 16): # randomized_select(A, 0, 14, i) # print i, '\t', A # print randomized_select(A, 0, 14, i)