Ejemplo n.º 1
0
def testcase(index, input_array, expected_output):
    print("\n-- testcase {} --".format(index))

    input_array_copy = input_array

    print("input array : {}".format(input_array))
    print("expected output : {}\n".format(expected_output))

    # bst sort
    bst_sort_result = bst_sort(input_array)
    print("bst sort: {}, {}".format(bst_sort_result,
                                    bst_sort_result == expected_output))

    # merge sort
    merge_sort_result = merge_sort(input_array)
    print("merge sort: {}, {}".format(merge_sort_result,
                                      merge_sort_result == expected_output))

    # quick sort
    quick_sort(input_array, 0, len(input_array) - 1)
    print("quick sort: {}, {}".format(input_array,
                                      input_array == expected_output))
    input_array = input_array_copy

    # heap sort
    heap_sort_result = heap_sort(input_array)
    print("heap sort: {}, {}".format(heap_sort_result,
                                     heap_sort_result == expected_output))
    def test_quick_sort(self):
        p = 0
        for array in self.arrays:
            r = len(array) - 1
            quick_sort(array, p, r)

        self.check_sorting()
Ejemplo n.º 3
0
def pair_fin(clos_app,dt, aa, src, freq,fbmamp,multweight=True,noiseweight=True,ovlpweight=True,cutoff=9000.*0.005*0.005,puv=False):
    final = []
    cnt, N = 0,len(clos_app)
    bm_intpl = export_beam.beam_interpol(freq,fbmamp,'cubic')
    if ovlpweight: #rbm2interp: FT of sq of beam
        fbm2 = n.multiply(fbmamp,fbmamp)   #element wise square for power beam
        rbm2 = n.fft.fft2(fbm2); rbm2 = n.fft.fftshift(rbm2)
        freqlm = n.fft.fftfreq(len(freq),d=(freq[1]-freq[0])); freqlm = n.fft.fftshift(freqlm)
        print "###small imaginary components are error, nothing to worry about"
        rbm2interp = interpolate.interp2d(freqlm, freqlm, rbm2, kind='cubic')
    for key in clos_app:
        cnt = cnt+1
        if (cnt/1000)*1000 == cnt:
            print 'Calculating baseline pair %d out of %d:' % (cnt,N)
        bl1,bl2 = key[0],key[1]
        t1,t2 = clos_app[key][1],clos_app[key][2]
        correlation,(uvw1,uvw2) = get_corr(aa, src, bm_intpl, t1,t2, bl1, bl2)
        if correlation == 0: continue
        if ovlpweight: ovlp = get_ovlp(aa,t1,t2,rbm2interp)
        else: ovlp = 1.
        weight = get_weight(aa,bl1,bl2,uvw1,multweight,noiseweight,ovlp)
        #while correlation > cutoff:
        if puv: final.append((weight*correlation,correlation,(bl1,t1,uvw1),(bl2,t2,uvw2)))
        else: final.append((weight*correlation,correlation,(bl1,t1),(bl2,t2)))
        #t1,t2 = t1+dt,t2+dt
        try: correlation,(uvw1,uvw2)  = get_corr(aa, src,bm_intpl, t1,t2, bl1, bl2)
        except(TypeError): correlation  = 0.
        else:
            if ovlpweight: ovlp = get_ovlp(aa,t1,t2,rbm2interp)
            else: ovlp = 1.
            weight = get_weight(aa,bl1,bl2,uvw1,multweight,noiseweight,ovlp)

    quick_sort.quick_sort(final,0,len(final)-1)
    return final
Ejemplo n.º 4
0
 def testQuick(self):
     result = copy(self.original)
     before = time.time()
     quick_sort(result)
     after = time.time()
     print("Quick Sort, size: %d time: %f" % (self.list_length, after-before))
     self.assertEqual(self.sorted_list, result, "Quick Sort Failed")
Ejemplo n.º 5
0
def test_quick_sort():
    case_1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    case_2 = list(case_1)
    case_2.reverse()
    expected = list(case_1)
    assert quick_sort(case_1) == expected
    assert quick_sort(case_2) == expected
Ejemplo n.º 6
0
 def test_quick_sort(self):
     arr = [8, 2, 4, 5, 7, 1]
     quick_sort(arr)
     self.assertEqual(arr, [1, 2, 4, 5, 7, 8])
     arr = [3, 9, 8, 4, 6, 10, 2, 5, 7, 1]
     quick_sort(arr)
     self.assertEqual(arr, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
 def test_quick(self):
     unsorted = [1, 2, 3, 4, 5]
     sorted_lst = [1, 2, 3, 4, 5]
     high = len(unsorted) - 1
     low = 0
     quick_sort(unsorted, low, high)
     self.assertEqual(sorted_lst, unsorted)
Ejemplo n.º 8
0
def best_and_worst_reviewed_products():
    """

    :return average_score_per_product: Sorted list of lists [product_id, average_score]
    """
    average_score_per_product = []
    cumulative_score_per_product = [[i + 1, 0] for i in range(number_products)]
    # Copying the list of lists is not working due to python binding, the element lists are bound
    sales_per_product_list = calculate_sales_per_product()

    for sale in lifestore_sales:
        product_id = sale[1]
        cumulative_score_per_product[product_id - 1][1] += sale[2]

    for cumulative_score in cumulative_score_per_product:
        product_id = cumulative_score[0]
        sales = sales_per_product_list[product_id - 1][1]
        # Only count them if they have been sold
        if sales > 0:
            average_score = cumulative_score[1] / sales
            average_score_per_product.append([product_id, average_score])

    # Sort the list from minimum to maximum
    quick_sort(average_score_per_product, lambda x: x[1])

    return average_score_per_product
Ejemplo n.º 9
0
def find_numbers(array, k):
    if len(array) < 2:
        return None
    if len(array) == 2:
        return array[0], array[1]

    length = len(array)
    quick_sort(array, 0, length - 1)
    print("sorted array: {}".format(array))

    low, high = 0, length - 1
    if array[low] + array[low + 1] >= k:
        return array[low], array[low + 1]

    if array[high] + array[high - 1] <= k:
        return array[high - 1], array[high]

    min_value = 1e10
    a, b = 0, 0
    while low < high:
        s = array[low] + array[high]
        if abs(s - k) <= min_value:
            min_value = abs(s - k)
            a = low
            b = high
        if s == k:
            return array[low], array[high]
        elif s > k:
            high -= 1
        else:
            low += 1
    return array[a], array[b]
Ejemplo n.º 10
0
def iterations(sort_type, n):  # This function sorts randomly generated numbers of length n that range from -500 to 500
	if sort_type == "selection sort":
		selection_sort.selection_sort([random.randint(-500,500) for number in range(n)])
	elif sort_type == "merge sort":
		merge_sort.merge_sort([random.randint(-500,500) for number in range(n)])
	elif sort_type == "quick sort":
		quick_sort.quick_sort([random.randint(-500,500) for number in range(n)])
Ejemplo n.º 11
0
def main():

    arr = [9,2,6,4,3,5,1]
    quick_sort(arr, 0, len(arr)-1)

    for i in range(len(arr)):
        print ("%d" %arr[i])
Ejemplo n.º 12
0
def bucket_sort(data_list,bucket_size = DEFAULT_BUCKET_SIZE):
    length = len(data_list)
    min = max = data_list[0]

    #寻找最小值和最大值
    for i in range(0,length):
        if data_list[i] < min:
            min = data_list[i]
        if data_list[i] > max:
            max = data_list[i]

    #定义多个桶并初始化
    num_of_buckets = (max - min) // bucket_size +1 
    buckets = []
    for i in range(num_of_buckets):
        buckets.append([])
    
    #将数据放入桶中
    for i in range(0,length):
        buckets[(data_list[i] - min)//bucket_size ].append(data_list[i])
    
    #依次对桶内数据进行快速排序
    data_list.clear()

    for i in range(num_of_buckets):
        print(f"第{i}个桶排序前的内容是{buckets[i]}")
        quick_sort(buckets[i])
        # print(f"第{i}个桶排序后的内容是{buckets[i]}")
        for data in buckets[i]:
            data_list.append(data) 
Ejemplo n.º 13
0
    def find_median(self, a, begin, end):
        # use quick sort to sort in place
        x = begin + (end - begin) // 2

        from quick_sort import quick_sort
        quick_sort(a, begin, end)

        return a[x]
def test_big_quick_sort():
    ints = [i for i in range(0,10000)]
    mixed_ints = [i for i in range(0,10000)]
    assert ints == mixed_ints
    random.shuffle(mixed_ints)
    assert ints != mixed_ints
    quick_sort(mixed_ints)
    assert ints == mixed_ints
def test_single_number_list():
    arr = [1]
    low = 0
    high = 0
    quick_sort(arr, low, high)
    actual = arr
    expected = [1]
    assert actual == expected
def test_quick_sort_edge_case_two():
    arr = ['a', 'c', 'bond', '1b']
    quick_sort(arr, 0, 3)
    assert arr == [
        '1b',
        'a',
        'bond',
        'c',
    ]
Ejemplo n.º 17
0
def get_times(lst, number_of_rep=10):
	times = [[], [], [], []] # last, rand, first, middle
	for x in range(number_of_rep):
		for index, fun in enumerate([quick_sort.partition_last, quick_sort.partition_rand, quick_sort.partition_first, quick_sort.partition_middle]):
			t1 = time.perf_counter()
			quick_sort.quick_sort(lst, 0, len(lst) - 1, fun)
			t1 = time.perf_counter() - t1
			times[index].append(t1)
	return zip(*times)
Ejemplo n.º 18
0
def test_sorting():
    import random
    datalist = [random.randint(0, 1e6) for i in xrange(100)]
    quick_sort(datalist)

    previous = datalist[0]
    for i in datalist[1:]:
        assert previous <= i
        previous = i
Ejemplo n.º 19
0
def test_quick_sort(build_list):
    x, y = build_list
    assert quick_sort(x) == y

    import random
    for i in xrange(100):
        x = [random.randint(10,100) for i in xrange(20)]
        y = merge_sort(x)
        z = quick_sort(x)
        assert y == z
Ejemplo n.º 20
0
def merge_quick_sort(L):
    """
    This function inputs the value of unsorted list and invokes split function in the file merge_sort to split the list into two halves
    Then the function invokes the quick_sort function, then again it invokes the merge function in the merge_sort file and returns the sorted list
    :param L: The list which has to sorted
    :return: sorted list
    """
    (half1, half2) = merge_sort.split(L)
    (l1, l2) = quick_sort.quick_sort(half1), quick_sort.quick_sort(half2)
    return merge_sort.merge(l1, l2)
Ejemplo n.º 21
0
def test_quick_sort(build_list):
    x, y = build_list
    assert quick_sort(x) == y

    import random
    for i in xrange(100):
        x = [random.randint(10, 100) for i in xrange(20)]
        y = merge_sort(x)
        z = quick_sort(x)
        assert y == z
Ejemplo n.º 22
0
def test_large_list_quick_sort():
    lst = [
        3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48, 71, -2, -60,
        16, 40, 8
    ]
    quick_sort(lst, 0, (len(lst) - 1))
    assert lst == [
        -60, -2, 2, 3, 4, 5, 8, 15, 16, 19, 26, 27, 36, 38, 40, 44, 46, 47, 48,
        50, 71
    ]
Ejemplo n.º 23
0
def menu_de_algoritmos():
    print("Analise de algoritmos separadamente")
    print("(1) - Quick Sort")
    print("(2) - Merge Sort")
    print("(3) - Heap Sort")
    print("(4) - Radix Sort")

    option = input("Escolha uma opção: ")

    quantity = [100, 1000, 10000, 100000]
    limit = 1000**2

    if option == '1':

        for i in quantity:
            lista = cria_lista(i, limit)

            inicio = time.time()
            quick_sort(lista, 0, len(lista))
            fim = time.time()
            result = fim - inicio
            print("O tempo de ordenação do quicksort em um vetor de {} elementos é de {} segundos.".format(i, result))

    elif option == '2':

        for i in quantity:
            lista = cria_lista(i, limit)

            inicio = time.time()
            merge_sort(lista)
            fim = time.time()
            result = fim - inicio
            print("O tempo de ordenação do mergesort em um vetor de {} elementos é de {} segundos.".format(i, result))

    elif option == '3':

        for i in quantity:
            lista = cria_lista(i, limit)

            inicio = time.time()
            heapsort(lista)
            fim = time.time()
            result = fim - inicio
            print("O tempo de ordenação do heap em um vetor de {} elementos é de {} segundos.".format(i, result))

    elif option == '4':

        for i in quantity:
            lista = cria_lista(i, limit)

            inicio = time.time()
            radix_sort(lista)
            fim = time.time()
            result = fim - inicio
            print("O tempo de ordenação do radix em um vetor de {} elementos é de {} segundos.".format(i, result))
Ejemplo n.º 24
0
def test_nearly_sorted():
    """
  A list of nearly sorted integers is sorted by QuickSort.
  """

    expected = [2, 3, 5, 7, 11, 13]

    lst = [2, 3, 5, 7, 13, 11]
    quick_sort(lst, 0, len(lst) - 1)

    assert lst == expected
Ejemplo n.º 25
0
def test_randomly_sorted():
    """
  A randomly sorted list of integers is sorted by QuickSort.
  """

    expected = [4, 8, 15, 16, 23, 42]

    lst = [8, 4, 23, 42, 16, 15]
    quick_sort(lst, 0, len(lst) - 1)

    assert lst == expected
Ejemplo n.º 26
0
def test_reverse_sorted():
    """
  A reverse sorted list of integers is sorted by QuickSort.
  """

    expected = [-2, 5, 8, 12, 18, 20]

    lst = [20, 18, 12, 8, 5, -2]
    quick_sort(lst, 0, len(lst) - 1)

    assert lst == expected
Ejemplo n.º 27
0
def test_few_uniques():
    """
  A list with few unique integers is sorted by QuickSort.
  """

    expected = [5, 5, 5, 7, 7, 12]

    lst = [5, 12, 7, 5, 5, 7]
    quick_sort(lst, 0, len(lst) - 1)

    assert lst == expected
Ejemplo n.º 28
0
def calculate_egalitarian_welfare(agents, rounds):
    welfares = []
    welfare_idx = []

    for idx, agent in enumerate(agents):
        welfares.append(agent.get_utility())
        welfare_idx.append(idx)

    quick_sort.quick_sort(welfares, welfare_idx, 0, len(agents) - 1)

    return welfares[0], welfares[len(agents) - 1]
def test_quick_sort_edge_case():
    arr = [
        2.5,
        -5,
        0,
        8,
        7,
        9,
    ]
    quick_sort(arr, 0, 5)
    assert arr == [-5, 0, 2.5, 7, 8, 9]
Ejemplo n.º 30
0
    def __vote_for_slots_highest_preference(self):
        # Rank in terms of highest preference
        quick_sort.quick_sort(self.__popular_time_slots_preference,
                              self.__popular_time_slots_idx, 0,
                              self.__n_slots_consideration - 1)

        # Vote for n_votes time-slots with the highest preference from the n_slots_consideration most popular time slots
        for idx in range(self.__n_slots_consideration - self.__n_votes,
                         self.__n_slots_consideration):
            self.environment.vote_time_slot(self.__popular_time_slots_idx[idx])
            self._time_slots_chosen.append(self.__popular_time_slots_idx[idx])
Ejemplo n.º 31
0
    def test_quick_sort(self):
        arr1 = [1, 5, 8, 4, 2, 9, 6, 0, 3, 7]
        arr2 = []
        arr3 = [2]
        arr4 = [0, 1, 2, 3, 4, 5]
        arr5 = random.sample(range(200), 50)

        self.assertEqual(quick_sort(arr1), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
        self.assertEqual(quick_sort(arr2), [])
        self.assertEqual(quick_sort(arr3), [2])
        self.assertEqual(quick_sort(arr4), [0, 1, 2, 3, 4, 5])
        self.assertEqual(quick_sort(arr5), sorted(arr5))
Ejemplo n.º 32
0
def sort_products_by_searches():
    """
    A function that calculates the number of searches per product and sorts them from best to worst
    and prints them
    :return searches_per_product_list: an ordered list
    """
    # holds the index and the number of searches of each product_id
    searches_per_product_list = calculate_searches_per_product()

    quick_sort(searches_per_product_list, lambda x: x[1])

    return searches_per_product_list
def test_quick_sort():
    for i in range(500):
        array = []

        for j in range(i):
            array.append(random.randrange(-i, i, 1))

        temp = array.copy()
        temp.sort()
        quick_sort(array)

        assert temp == array
Ejemplo n.º 34
0
def pair_sort(pairings, bm_intpl, cutoff=0.):
    sorted = []
    for key in pairings:
        L = len(pairings[key])
        for i in range(L):  # get the points pairwise
            for j in range(i+1,L):
                pt1,pt2 = pairings[key][i],pairings[key][j]
                duv = tuple(x - y for x,y in zip(pt1[2], pt2[2]))
                val = export_beam.get_overlap(bm_intpl,*duv)
                if abs(val) > cutoff:
                    sorted.append((val,(pt1[0],pt1[1]),(pt2[0],pt2[1]),pt1[2]))
    quick_sort.quick_sort(sorted,0,len(sorted)-1)
    return sorted
Ejemplo n.º 35
0
def counting_element(s): 
	#if array is empty, force quit 
	if len(s) == 0: return 

	#sort an array 
	s = quick_sort(s)

	previous = s[0] # set previous to the first element in that array 
	count = 0 # count is used to keep track of the element 
	new_array = [] #this array is used to store the count elemnt 
	new_array.append(count) #create first element of empty array 
	j = 0 

	#go through the array and find the repeated elemnt of that aray
	for i in range(0,len(s)): 
		if s[i] == previous: 
			count = count + 1
			new_array[j] = count 
		else: 
			#print("element:{0},appear:{1}".format(previous,count))
			previous = s[i] # set previous to the next element 
			count = 1 #reset this couting to 1
			j = j + 1 # move to the next element of new_array
			new_array.append(count) # append to the next count of new element 
	#print("element:{0},appear:{1}".format(previous,count))
	return new_array 
Ejemplo n.º 36
0
def test_stability():
    """Test the statbility of the quick sort."""
    from quick_sort import quick_sort
    lst = [(2, 'ab'), (1, 'ba'), (3, 'ab'), (2, 'ba'), (5, 'ab')]
    one = lst[0]
    two = lst[3]
    sort_lst = quick_sort(lst)
    assert sort_lst == [(1, 'ba'), (2, 'ab'), (2, 'ba'), (3, 'ab'), (5, 'ab')]
    assert sort_lst[1] is one
    assert sort_lst[2] is two
Ejemplo n.º 37
0
def return_k_element(s,k): 
	count_element = counting_element(s)
	s = remove_sort(s)
	dictionary = put_to_dict(s,count_element)
	dictionary2 = quick_sort([(value,key) for  (key,value) in dictionary.items()])

	array_k = []
	i = 0

	while i <k: 
		array_k.append(dictionary2[i][1])
		i = i+1

	return array_k
Ejemplo n.º 38
0
def main():
  if len(sys.argv) != 2:
    print 'usage: ./compare_sort_algos.py --len_of_array'
    sys.exit(1)

  len_of_array = sys.argv[1] # This argument has length of the array to be sorted.
  print len_of_array
  # Create Random numbers of this length. The random numbers generated are unique.
  array = random.sample(xrange(10000000), int(len_of_array))
  #print array
  sorted_array = insertion_sort.insertion_sort(array)
  insertion_time = time.clock()
  insertion_tot = insertion_time - start_time
  print ("Insertion Sort %s" % insertion_tot)
  sorted_array = selection_sort.selection_sort(array)
  selection_time = time.clock()
  selection_tot = selection_time - insertion_time
  print ("Selection Sort %s" % (selection_tot))
  sorted_array = bubble_sort.bubble_sort(array)
  bubble_time = time.clock()
  bubble_tot = bubble_time - selection_time
  print ("Bubble Sort %s" % (bubble_tot))
  sorted_array_m = merge_sort.merge_sort(array)
  merge_time = time.clock()
  merge_tot = merge_time - bubble_time
  print ("Merge Sort %s" % (merge_tot))
  sorted_array_q = quick_sort.quick_sort(array)
  quick_time = time.clock()
  quick_tot = quick_time - merge_time
  print ("Quick Sort %s" % (quick_tot))
  sorted_array_h = heap_sort.heap_sort(array)
  heap_time = time.clock()
  heap_tot = heap_time - quick_time
  print ("Heap Sort %s" % (heap_tot))
  
  objects = ('Insertion', 'Selection', 'Bubble', 'Merge','Quick','Heap')
  y_pos = np.arange(len(objects))
  performance = [insertion_tot/merge_tot,selection_tot/merge_tot,bubble_tot/merge_tot,merge_tot/merge_tot,quick_tot/merge_tot,heap_tot/merge_tot]
 
  if (sorted_array_m == sorted_array_q):
	print "Merge and Quick sorts are giving the same sorted array results"
  plt.bar(y_pos, performance, align='center', alpha=0.5)
  plt.xticks(y_pos, objects)
  plt.ylabel('Time taken w.r.t merge sort')
  plt.title('Sorting Techniques')
 
  plt.show()
def test_reverse():
    reverse_list = [15, 10, 9, 8, 7, 5, 2, 0]
    sorted_reverse = quick_sort(reverse_list)
    assert sorted_reverse == sorted(reverse_list)
Ejemplo n.º 40
0
 def test_sorts_no_items(self):
     arr = []
     quick_sort(arr)
     self.assertEqual([], arr)
Ejemplo n.º 41
0
 def xtests_sorts_many_items(self):
     arr = [4, 1, 2, 2, 1, 3, 3]
     quick_sort(arr)
     self.assertEqual([1, 1, 2, 2, 3, 3, 4], arr)
def test_simple():
    simple_list = [10, 7, 8, 9, 2, 15, 0, 5]
    sorted_simple = quick_sort(simple_list)
    assert sorted_simple == sorted(simple_list)
Ejemplo n.º 43
0
def test_quicksort_01():
    k = 10000
    rand_list = [random.randint(-k, k) for i in xrange(k)]
    copy_of_list = rand_list[:]
    Q.quick_sort(rand_list)
    assert rand_list == sorted(copy_of_list)
Ejemplo n.º 44
0
 def test_quick_sort(self):
     self.assertEqual(quick_sort.quick_sort(self._arr), self._res)
Ejemplo n.º 45
0
def test_random_lst():
    """Test that a random list is sorted."""
    from quick_sort import quick_sort
    lst_sort = sorted(rand_lst)
    assert quick_sort(rand_lst) == lst_sort
Ejemplo n.º 46
0
def test_quick_sort_empty():
    """Test that was can pass an empty list."""
    from quick_sort import quick_sort
    assert quick_sort([]) == []
def test_float():
    float_list = [10, 7, 8, 9.5, 2.5, 15, 0, 5]
    sorted_float = quick_sort(float_list)
    assert sorted_float == sorted(float_list)
Ejemplo n.º 48
0
import quick_sort


l = [[1, 5, 36, 67, 4, 7, 78, 100], [111, 23, 111], [1], []]
result_sort = [[1, 4, 5, 7, 36, 67, 78, 100], [23, 111, 111], [1], []]
for i in range(len(l)):
    try:
        ret_sort = quick_sort.quick_sort(l[i])
        if ret_sort == result_sort[i]:
            print 'success', ret_sort
        else:
            print 'error1 : The %sth sorted %s is not equal to the expected result %s' % \
                  ( i, ret_sort, result_sort[i])
    except:
        print 'select sort exception:', i



Ejemplo n.º 49
0
 def test_quick_sort(self):
     result = quick_sort(self.arr)
     self.assertEqual(result, self.answer)
def test_already_sorted():
    already_sorted = [0, 2, 5, 7, 8, 9, 10, 15]
    sorted_already = quick_sort(already_sorted)
    assert sorted_already == sorted(already_sorted)
def test_repeat():
    repeat_list = [10, 7, 8, 9, 2, 15, 0, 5, 15]
    sorted_repeat = quick_sort(repeat_list)
    assert sorted_repeat == sorted(repeat_list)
Ejemplo n.º 52
0
 def test_quick_sort_correctly_sorts(self):
     sorted_values = quick_sort(self.unsorted_values)
     self.assertEqual(sorted(self.unsorted_values), sorted_values)
Ejemplo n.º 53
0
def external_merge_sort(infilename, outfilename, word_size = 4, memory_limit = 1024*1024):
    
    TEMP_FILE_NAME = "temp.dat"

    with open(infilename, "rb") as infile:
        infile.seek(0, 2)
        infile_size = infile.tell()
        infile.seek(0, 0)

        with open(TEMP_FILE_NAME, "wb+") as temp_file, \
             open(outfilename, "wb+") as out_file:

            # Phase 1: sort parts
            partsCount = 0
            while infile.tell() < infile_size:
                # print "infile.tell():", infile.tell()
                bytes_left = (infile_size - infile.tell())
                # values = array.array('I') # array of long integers
                values = array.array('B')
                values.fromfile(infile, min(memory_limit, bytes_left)/values.itemsize) # read integers

                # print "sorting part", partsCount + 1
                quick_sort(values,partition_func = splitByMedian, leaf_sort_func = leaf_insertion_sort,trace=False)
                # radix_sort(values, 256);
                # print "after sort:", values

                values.tofile(temp_file)
                partsCount += 1

            # Phase 2: n-way merge
            streamsList = []
            for partIndex in xrange(partsCount):
                streamsList.append(Stream(temp_file, partIndex*memory_limit, \
                                          min((partIndex+1)*memory_limit, infile_size), word_size))

            # for stream in streamsList:
            #     print stream

            out_buffer = array.array('B');
            current_words = [stream.getWord() for stream in streamsList];

            while len(streamsList) > 0:
                minIndex, minWord = min(enumerate(current_words), key=lambda e: e[1])
                # minStream = streamsList[0]
                # minWord   = minStream.getWord() 
                # for stream in streamsList[1:]:
                #     word = stream.getWord()
                #     # print "word: {}, minWord: {}".format(word.encode('hex'), minStream.getWord().encode('hex'))
                #     if word < minWord:
                #         minStream = stream
                #         minWord = word

                # print "writing: {}".format(minStream.getWord().encode('hex'))
                out_buffer.append(minWord)
                if out_buffer.buffer_info()[1] > 1024:
                    out_buffer.tofile(out_file)
                    out_buffer = array.array('B');
                    # out_file.write(minStream.getWord())
                
                if streamsList[minIndex].next():
                    current_words[minIndex] = streamsList[minIndex].getWord()
                else:
                    del streamsList[minIndex]
                    del current_words[minIndex]

            out_buffer.tofile(out_file)
Ejemplo n.º 54
0
 def tests_sorts_one_item(self):
     arr = [1]
     quick_sort(arr)
     self.assertEqual([1], arr)
Ejemplo n.º 55
0
def test_quicksort_03():
    k = 10000
    rand_list = [random.randint(-k, k) for i in xrange(k)]
    copy_of_list = rand_list[:]
    Q.quick_sort(rand_list, pivot_mode='best_of_three')
    assert rand_list == sorted(copy_of_list)
Ejemplo n.º 56
0
 def tests_sorts_two_items(self):
     arr = [2, 1]
     quick_sort(arr)
     self.assertEqual([1, 2], arr)
Ejemplo n.º 57
0
 def test_quick_sort_returns_an_array(self):
     sorted_values = quick_sort(self.unsorted_values)
     assert isinstance(sorted_values, list)
def test_long():
    long_list = range(10000)
    shuffle(long_list)
    sorted_long = quick_sort(long_list)
    assert sorted_long != long_list
    assert sorted_long == sorted(long_list)