def test_partition(self): pivot_index = sort.partition(0, len(self.list), self.list) for e in self.list[0:pivot_index]: self.assertGreaterEqual(self.list[pivot_index], e) for e in self.list[pivot_index:]: self.assertGreaterEqual(e, self.list[pivot_index])
def select(source, start, end, k): if (end - start) <= 140: sort.normal_quick_sort(source, start, end) return [source[k - 1], k-1] length = end - start for i in xrange(length/5): sort.insert_sort(source,start + i*5, start + i*5 + 5) temp = source[start + i] source[start + i] = source[start + 5*i + 2] source[start + 5*i + 2] = temp [i, index] = select(source, start, start + length/5, length/10) temp = source[index] source[index] = source[end - 1] source[end - 1] = temp j = sort.partition(source, start, end) if j == k: return [source[j], j] elif j > k: return select(source, start, j, k) else: return select(source, j + 1, end, k)
def select(source, start, end, k): if (end - start) <= 140: sort.normal_quick_sort(source, start, end) return [source[k - 1], k - 1] length = end - start for i in xrange(length / 5): sort.insert_sort(source, start + i * 5, start + i * 5 + 5) temp = source[start + i] source[start + i] = source[start + 5 * i + 2] source[start + 5 * i + 2] = temp [i, index] = select(source, start, start + length / 5, length / 10) temp = source[index] source[index] = source[end - 1] source[end - 1] = temp j = sort.partition(source, start, end) if j == k: return [source[j], j] elif j > k: return select(source, start, j, k) else: return select(source, j + 1, end, k)
def test_partion(self): self.assertEqual(sort.partition([3, 7, 2, 1, 5, 4], 0, 5), 3)
def test_partitioning_when_sequence_with_duplicates_given(): sequence = ['A', 'A', 'B', 'B', 'A', 'B', 'A', 'A', 'A', 'B', 'A', 'A'] expected = ['A', 'A', 'A', 'A', 'A', 'A', 'B', 'A', 'B', 'B', 'B', 'A'] assert_equal(partition(sequence, lo=0, hi=len(sequence)-1), expected)
def test_partitioning(): assert_equal(partition([5, 4, 2, 11, 10], lo=0, hi=4), [2, 4, 5, 11, 10])