a = [] f = open("../data/qsort_input.txt", "r") for l in f.readlines(): if len(l) > 0: num = int(l) a.append(num) import sort_utils b = [] b.extend(a) c = [] c.extend(a) comps = qsort(a, 0, len(a) - 1, pickFirstElementAsPivot) sort_utils.verify_sort(a) print "a comparisons", comps b[0], b[-1] = b[-1], b[0] comps = qsort(b, 0, len(b) - 1, pickLastElementAsPivot) sort_utils.verify_sort(b) print "b comparisons", comps p = pickMedianElementAsPivot(c, 0, len(c) - 1) c[0], c[p] = c[p], c[0] comps = qsort(c, 0, len(c) - 1, pickMedianElementAsPivot) sort_utils.verify_sort(c) print "c comparisons", comps
def merge_sort(arr, aux, lo, hi): if hi > lo: mid = lo + (hi - lo) // 2 merge_sort(arr, aux, lo, mid) merge_sort(arr, aux, mid + 1, hi) merge(arr, aux, lo, mid, hi) def merge(arr, aux, lo, mid, hi): for i in range(lo, hi+1): aux[i] = arr[i] pa, pb = lo, mid + 1 for i in range(lo, hi+1): if pa > mid: arr[i] = aux[pb] pb += 1 elif pb > hi: arr[i] = aux[pa] pa += 1 elif aux[pa] > aux[pb]: arr[i] = aux[pb] pb += 1 else: arr[i] = aux[pa] pa += 1 a = sort_utils.generate_random_array(10000) random.shuffle(a) merge_sort_top_down(a) sort_utils.verify_sort(a)
for i in aux: counts[nth_digit(i, s, radix)] += 1 accum = 0 for i in range(radix): old_count = counts[i] counts[i] = accum accum += old_count for i in aux: digit = nth_digit(i, s, radix) ordered[counts[digit]] = i counts[digit] += 1 aux, ordered = ordered, aux return aux import sort_utils a = sort_utils.generate_random_array(1000000) # print a b = counting_sort(a) # print b sort_utils.verify_sort(b) b = radix_sort(a) # print b sort_utils.verify_sort(b)