Example #1
0
def run_program():
    pygame.init()
    screen = pygame.display.set_mode((900, 650))
    sr_setting = Setting()
    pygame.display.set_caption("Sorting alogrithms")
    fnt = pygame.font.SysFont("comicsans", 25)
    fnt1 = pygame.font.SysFont("comicsans", 30)
    array = [0] * 151
    arr_color = [sr_setting.Green] * 151
    clr = [
        sr_setting.Green, sr_setting.Red, sr_setting.Dark_blue,
        sr_setting.Orange, sr_setting.bg_color
    ]
    pf.shuffel_arr(array)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    sys.exit()
                if event.key == pygame.K_m:
                    ms.mergesort(array, 1,
                                 len(array) - 1, arr_color, clr, screen, fnt,
                                 fnt1)
                if event.key == pygame.K_b:
                    bs.bubblesort(array, arr_color, clr, screen, fnt, fnt1)
                if event.key == pygame.K_s:
                    qs.quicksort(array, arr_color, clr, screen, fnt, fnt1)
        screen.fill(sr_setting.bg_color)
        pf.draw(screen, fnt, fnt1, array, arr_color, clr)
        pygame.display.flip()
def coo_to_csc(N, col, row, data):
    quicksort((col, row, data), 0, len(data))
    k = 0
    # merge same cords
    for i in range(1, len(data)):
        if col[k] != col[i] or row[k] != row[i]:
            k += 1
            col[k], row[k], data[k] = col[i], row[i], data[i]
        else:
            data[k] += data[i]

    data, row = data[:k + 1], row[:k + 1]
    # create colptr
    col.resize(len(data) + 1, refcheck=False)
    k = 0
    c = col[0]
    for i in range(1, len(data)):
        c1 = col[i]
        if c1 != c:
            k += 1
            col[k] = i
        c = c1
    col[k + 1] = len(data)
    col = col[:k + 2]

    return col, row, data
 def test_random_list(self):
     random_sz = randint(1, 2000)
     a = [randint(-2000, 5000) for i in range(0, random_sz)]
     b = a[:]
     quicksort(a)
     b.sort()
     self.assertEqual(a, b)
Example #4
0
def main():
    """
    bubblesort的时间复杂度是O(n^2)
    quicksort的时间复杂度是O(nlogn)
    """
    # csv_path = "./bubblesort.csv"
    csv_path = "./quicksort.csv"

    nsample = 1
    N = list(range(10, 10000, 10))
    avg_elapsed = 0
    for n in N:
        for _ in range(nsample):
            l = [random.randint(0, 10000) for _ in range(n)]
            start = time.clock()
            # bubblesort(l)
            quicksort(l)
            elapsed = (time.clock() - start)
            # print("Time used:", elapsed)
            avg_elapsed += elapsed
        avg_elapsed /= nsample
        print("n:", n)
        print("Average time used:", avg_elapsed)

        if not os.path.exists(csv_path):
            f = open(csv_path, "w")
            f_csv = csv.writer(f)
            f_csv.writerow(["N", "avg_elapsed"])
            f_csv.writerow((n, avg_elapsed))
        else:
            f = open(csv_path, "a")
            f_csv = csv.writer(f)
            f_csv.writerow((n, avg_elapsed))
        avg_elapsed = 0
Example #5
0
 def test__sort(self):
     data = [1, 3, 2, 8]
     quicksort(data, 0, len(data) - 1)
     self.assertEqual([1,2,3, 8], data)
     
     data1 = [150, 4, 2, 7, 1, 9, 160]
     quicksort(data1, 0, 6)
     self.assertEqual([1, 2, 4, 7, 9, 150, 160], data1)
Example #6
0
def test_quick(l, mid_pivot=True):
	result = 0	
	for x in range(10):
		arr = copy(l)
		t = time.time()
		quicksort(l, mid_pivot=mid_pivot)
		result += time.time() - t
	return result
    def test_quicksort(self):
        for j in range(10):
            l = rand_list(max_list=100)

            # no return!
            quicksort(l)

            for i in range(0, len(l) - 1):
                self.assertLessEqual(l[i], l[i + 1])
Example #8
0
 def test_sorting_correctness(self):
     """It should sort correctly despite pivot selection strategy"""
     unsorted_array = [3, 8, 2, 5, 1, 4, 7, 6]
     sorted_array_with_first, _ = quicksort.quicksort(unsorted_array, quicksort.select_first)
     sorted_array_with_last, _ = quicksort.quicksort(unsorted_array, quicksort.select_last)
     sorted_array_with_middle, _ = quicksort.quicksort(unsorted_array, quicksort.select_middle)
     self.assertEqual(sorted_array_with_first, [1, 2, 3, 4, 5, 6, 7, 8])
     self.assertEqual(sorted_array_with_first, sorted_array_with_last)
     self.assertEqual(sorted_array_with_first, sorted_array_with_middle)
    def testSort(self):
        a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        self.assertEqual(quicksort.quicksort(a), [1, 2, 3, 4, 5, 6, 7, 8, 9])

        b = [8, 7, 6, 5, 4, 3, 2, 1]
        self.assertEqual(quicksort.quicksort(b), [1, 2, 3, 4, 5, 6, 7, 8])

        c = [1, 6, 3, 2, 1, 9, 7, 5, 4, 9]
        self.assertEqual(quicksort.quicksort(c),
                         [1, 1, 2, 3, 4, 5, 6, 7, 9, 9])
Example #10
0
 def sortPoints(pList, coord_str):
     if (coord_str == "x"):
         # Sort by x-coords
         quicksort.quicksort(pList, 0, len(pList)-1, pointUtils.compareX)
     elif (coord_str == "y"):
         # Sort by y-coords
         quicksort.quicksort(pList, 0, len(pList)-1, pointUtils.compareY)
     else:
         # Print error and get out.
         print "ERROR: pointUtils.sortPoint(): Please use param x or y"
Example #11
0
def main ( ):
    menu ( )
    for i in range ( len ( gb.n ) + 1 ):
        m, gb.time = gb.n [ :i ], 0
        quicksort ( m, 0, len ( m ) - 1 )
        gb.parameters.append ( ( len ( m ), gb.time ) )
    print ( "\n\tSorted list: ", m, "\n" )
    print ( "\n\tQuicksort Parameters: ", gb.parameters )
    print ( "\n\tPartition Parameters: ", gb._parameters )
    graph ( )
Example #12
0
 def test_integers_sort(self):
     for i, input in enumerate(range(100)):
         input = random.sample(range(0, 1000), 16)
         size = len(input) - 1
         expected = sorted(input)
         quicksort(input, 0, size)
         print(
             "\n----------Test#:{}----------\nInput: {}\nExpected: {}\nResult: {}\n"
             .format((i + 1), input, expected, input == expected))
         self.assertEqual(input, expected)
Example #13
0
    def test_quicksort(self):
        # reverse order input
        arr = [5, 4, 3, 2, 1]
        sorted_arr = quicksort(arr)
        assert sorted_arr == [1, 2, 3, 4, 5]

        # already sorted
        arr = [1, 2, 3, 4, 5]
        sorted_arr = quicksort(arr)
        assert sorted_arr == [1, 2, 3, 4, 5]
Example #14
0
def test_quicksort():
    input = [8, 7, 4, 2, 6, 5, 3, 1]
    arr = input[:]
    quicksort(arr)
    assert arr, sorted(input)

    input = [randrange(1, 100) for x in range(100)]
    arr = input[:]
    quicksort(arr)
    assert arr, sorted(input)
Example #15
0
def testRandom():
    print("Beginning testRandom:")
    arr = []
    low = 0
    high = 1000
    fillArrayRandom(arr, ELEMENTS, low, high)
    quicksort(arr)
    if not isSorted(arr):
        print(arr)
    assert (isSorted(arr))
    print("*****\tPASS\t*****")
Example #16
0
    def test_quicksort(self):
        arr = []
        self.assertEqual(quicksort(arr), [])

        arr = [i for i in range(9, -1, -1)]
        self.assertEqual(quicksort(arr), [i for i in range(10)])

        arr = [5, 6, 1, 3, 8, 2, 1]
        self.assertEqual(quicksort(arr), [1, 1, 2, 3, 5, 6, 8])

        arr = [10, 20, 30, 10, 12, 21, 1]
        self.assertEqual(quicksort(arr), [1, 10, 10, 12, 20, 21, 30])
def test_quicksort():
    test_list = [randint(1, 50) for i in range(15)]
    test_sorted = test_list[:]
    quicksort(test_sorted, 0, 14)
    if test_sorted == sorted(test_list):
        print("test passes")
        print(test_list)
        print(test_sorted)
    else:
        print("test fails")
        print(test_list)
        print(test_sorted)
Example #18
0
def test_binary_search():
    items = []

    for i in range(1000):
        items.append(random.randint(0, 999))

    quicksort(items, 0, len(items) - 1)

    for i in range(100):
        assert binary_search(items, random.choice(items))
    assert not binary_search(items, -1)
    assert not binary_search(items, 1000)
Example #19
0
 def test5(self):
     """
     Test of other's quicksort
     """
     numElements = 10
     testlist = [random.randint(0, 10) for r in xrange(numElements)]
     # testlist = random.sample(xrange(999999999), numElements)
     answer = sorted(testlist)
     start = time.time()
     quicksort.quicksort(testlist, 0, len(testlist) - 1)
     elapsed = (time.time() - start)
     print 'In place takes %s' % str(elapsed)
     self.assertLessEqual(testlist, answer)
Example #20
0
def checkpairsumaftersorting(arr, x):
	quicksort.quicksort(arr, 0, len(arr)-1)
	print arr
	i = 0
	j = len(arr)-1
	while (i<j):
		if arr[i]+arr[j] > x:
			j -= 1
		if arr[i]+arr[j] < x:
			i += 1
		if arr[i]+arr[j] == x:
			return True
	return False
Example #21
0
    def add_edge(self, from_vertex, to_vertex, weight=0):
        self.graph_dict[from_vertex.value].add_edge(to_vertex.value, weight)

        if not self.directed:
            self.graph_dict[to_vertex.value].add_edge(from_vertex.value,
                                                      weight)

        if len(list(self.graph_dict[from_vertex.value].edges)) > 1:
            edges = list(self.graph_dict[from_vertex.value].edges.keys())
            quicksort(edges, 0, len(edges) - 1)
            zeros = [0 for i in range(len(edges))]
            new_edges = {key: value for key, value in zip(edges, zeros)}
            self.graph_dict[from_vertex.value].edges = new_edges
Example #22
0
def pair_sum(arr, target):
    quicksort(arr)
    start_index = 0
    end_index = len(arr) - 1

    while start_index < end_index:
        sum = arr[start_index] + arr[end_index]
        if sum == target:
            return arr[start_index], arr[end_index]
        elif sum < target:
            start_index += 1
        else:
            end_index -= 1

    return None, None
def find2num(array, sum):
	global global_init
	if not global_init:
		quicksort(array)
		global_init = True
		print "Init Finish"
		print "sort:", array
	length = len(array)
	pos = -1
	for i in range(0, length - 1):
		pos = binarysearch(array, sum - array[i], i + 1, length - 1)
		if pos >= 0:
			print array[i], ",", array[pos]
			return True
	return False
Example #24
0
 def test_long_unsorted_list(self):
     long_unsorted_list = [
         12, 3, 4, 12, 4, 35, 6, 7, 23, 4, 5, 6, 46, 43, 1, 1, 111, 2, 3, 4,
         535, 6, 53, 45, 2, 21, 4, 52, 3, 4, 5, 6, 345, 32, 42
     ]
     self.assertEqual(quicksort(long_unsorted_list),
                      sorted(long_unsorted_list))
Example #25
0
	def performRecognition(self,contour):
		contour = contour.replace('A','u').replace('S','r').replace('D','d')
		songs = midiSong.findSong(contour) 
		if songs == None:
			return songs
		elif (len(songs) == 50):
			self.failuretype = True
			return None
		else:
			print(len(songs))
			if (self.sorttype == "occ"):
				quicksort.quicksort(songs)
				songs.reverse()
			else:
				stringSort.stringSort(songs, self.sorttype)
			return songs
Example #26
0
    def test_swap_checks_correctness(self):
        """It should calculcate swap checks correctly"""
        # because it is in decreasing order, we will check it 5 + 4 + 3 + 2 + 1 times
        unsorted_array = [6, 5, 4, 3, 2, 1]
        _, number_of_checks = quicksort.quicksort(unsorted_array, quicksort.select_first)

        self.assertEqual(number_of_checks, 15)
Example #27
0
def test_sorted_list():
    """A sorted list will return unchanged"""
    lst = ['A', 'B', 'C', 'D', 'E']

    expected = ['A', 'B', 'C', 'D', 'E']
    actual = quicksort(lst)
    assert actual == expected
Example #28
0
def test_single_item_list():
    """A one-itemed list will return unchanged"""
    lst = ['A']

    expected = ['A']
    actual = quicksort(lst)
    assert actual == expected
Example #29
0
def test_backward_list():
    """A backward list will return reversed"""
    lst = ['E', 'D', 'C', 'B', 'A']

    expected = ['A', 'B', 'C', 'D', 'E']
    actual = quicksort(lst)
    assert actual == expected
Example #30
0
def sorttest(N,M):
    attempts = 100
    print("Testing...")
    timelist = []
    for k in range(attempts):
        n = random.randint(2,N)
        array = []
        for i in range(n):
            array.append(random.randint(0,M))
        correct = bubblesort.bubblesort(array)
        t0 = time.time()
        #INPUT ALGORITHM TO TEST HERE:#
        testanswer = quicksort.quicksort(array)
        ###############################
        timelist.append(time.time()-t0)
        if testanswer != correct:
            print("Error detected!")
            print("Input Array = ",array)
            print("Answer: ",testanswer)
            print("Desired: ",correct)
            return
    print("OK! - ",attempts," trials completed.")
    mean_time = sum(timelist)/len(timelist)
    print('Average time: ', round(mean_time,8)," seconds")
    return 
Example #31
0
 def performRecognition(self, contour):
     contour = contour.replace('A', 'u').replace('S', 'r').replace('D', 'd')
     songs = midiSong.findSong(contour)
     if songs == None:
         return songs
     elif (len(songs) == 50):
         self.failuretype = True
         return None
     else:
         print(len(songs))
         if (self.sorttype == "occ"):
             quicksort.quicksort(songs)
             songs.reverse()
         else:
             stringSort.stringSort(songs, self.sorttype)
         return songs
Example #32
0
def test_randomly_unsorted_list():
    """An unsorted list returns sorted"""
    lst = [3, 2, 4, 5, 1, 6]

    expected = [1, 2, 3, 4, 5, 6]
    actual = quicksort(lst)
    assert actual == expected
def radix_sort_str(instr):
    """The radix sort algorithm implemented for strings. Sorts lexico-
    graphically.
    """
    li = instr[:]

    length = 0
    for i in li:
        if len(i) > length:
            length = len(i)

    buckets = {}

    i = length - 1
    while i >= 0:
        for word in li:
            try:
                bucket = buckets.setdefault(word[i], Queue())
            except IndexError:
                bucket = buckets.setdefault('0', Queue())

            bucket.queue(word)

        li = []

        #quicksort is used here to get the buckets out in lexicographical
        #order because calling radix_sort_str again would result in an
        #infinite recursion.
        for key in quicksort(buckets.keys()):
            while buckets[key].size():
                li.append(buckets[key].dequeue())

        i -= 1

    return li
Example #34
0
def test_empty_list():
    """An empty list will return unchanged"""
    lst = []

    expected = []
    actual = quicksort(lst)
    assert actual == expected
def test_quicksort(seq: list) -> None:
    """Verify QuickSort works."""
    expected = sorted(seq)

    actual = quicksort.quicksort(seq)

    assert actual == expected
Example #36
0
def main():
    n = int(input("Enter the number of items you would like to sort: "))
    myList = []
    for index in range(n):
        myList.append(random.randint(1, n))


#    print("Unsorted List:",myList)
    start = time.perf_counter()

    quicksort(myList)

    endSort = time.perf_counter()

    #    print( "Sorted List:  ",myList)
    print("Total quick sort time of", n, "random items", endSort - start)
Example #37
0
 def createNewGen(self, prozent):
     list = self.shortTourlist(prozent)
     newlist = []
     for i in range(len(self.tourlist)):
         a = randint(0, len(list) - 1)
         b = randint(0, len(list) - 1)
         newlist.append(self.crossover(list[a], list[b]))
     self.tourlist = quicksort(newlist + list, compare_fitness)[:100]
     self.mutiere()
Example #38
0
def mergesort(n, size = 10):
  L = len(n)
  if L < size:
    return quicksort(n)
  else:
    a = mergesort(n[:L//2], size)
    b = mergesort(n[L//2:], size)

    return merge(a, b)
def test_quicksort_neg():
    """Test that quicksort handles negative integers."""
    assert quicksort([
        9567, 3472, 667, -200966, 34567, 87, 43334124, -2985, 287493, -245964,
        1, 6, 903
    ]) == [
        -245964, -200966, -2985, 1, 6, 87, 667, 903, 3472, 9567, 34567, 287493,
        43334124
    ]
def test_quicksort_two():
    """Tests quicksort output return is correctly sorted."""
    assert quicksort([
        9567, 3472, 667, 200966, 34567, 87, 43334124, 2985, 287493, 245964, 1,
        6, 903
    ]) == [
        1, 6, 87, 667, 903, 2985, 3472, 9567, 34567, 200966, 245964, 287493,
        43334124
    ]
Example #41
0
def find2num(array, sum):
	# init
	global global_init
	if not global_init:
		quicksort(array)
		global_init = True
		print "Init Finish"
	# check
	low = 0
	high = len(array) - 1
	while low < high:
		if array[low] + array[high] < sum:
			low += 1
		elif array[low] + array[high] > sum:
			high -= 1
		else:
			print "find:", array[low], ",", array[high]
			return True		
	return False
def test_quicksort_with_lots_of_random_lists():
    """Test quicksort with many random lists."""
    from quicksort import quicksort

    for i in range(100):
        list_length = random.randint(0, 100)
        unsorted_list = []
        for x in range(list_length):
            unsorted_list.append(random.randint(0, 100))
        assert quicksort(unsorted_list) == sorted(unsorted_list)
Example #43
0
    def draw(self,surface, relative=0):

        spritedict = self.spritedict
        items = spritedict.items()

        dirty = self.lostsprites
        self.lostsprites = []

        #Z Buffer

        #test if the obj is being visualized in the screen now.
        # if not, they dont need to be z-buffered
        v = self.viewport.colliderect
        zlevel = [item for item in items if v(item[0].rect)]
        

        if zlevel.__len__() > 0:
            quicksort.quicksort(zlevel,0,zlevel.__len__()-1)
            
            #zlevel.sort(cmp)
            
            a = range(zlevel.__len__())
            a.reverse()

            for k in a:
                s,r = zlevel[k]
                
                r = copy.copy(s.rect)
                if self.relative:
                    r.top -=  self.viewport.top
                    r.left-=  self.viewport.left
                
                newrect = surface.blit(s.image,r.topleft)

                if r is not 0:
                    dirty.append(newrect.union(r))
                else:
                    dirty.append(newrect)

                spritedict[s] = newrect
                
            return dirty
Example #44
0
def testRandom():
    arr = []
    # Range for random integers
    low, high = 0, 1000
    print("\nRunning testRandom:")

    # Insert random elements
    for _ in range(ELEMENTS):
        arr.append(randint(low, high))

    # Sort array
    quicksort(arr)

    # Ensure we can find all the elements in the array
    for num in arr:
        if (binarySearch(arr, num) == -1):
            print("Error: number {} not found in array".format(\
                num))
        #assert(binarySearch(arr, num) != -1)
    print("***** PASS *****")
Example #45
0
def main(args):
    numbers = get_values(args[0])
    if (len(numbers) <= 0):
        sys.exit(84)
    print(len(numbers), " element", sep="", end="")
    print("s" if len(numbers) > 1 else "")
    selection(numbers[::])
    insertion(numbers[::])
    bubble(numbers[::])
    print_res("Quicksort:", 0 if (len(numbers) <= 1) else quicksort(numbers[::])[1])
    print_res("Merge sort:", merge(numbers[::])[1])
    def test_randomly(self):

        for each_pass in range(0, 1000):
            random_list = []
            for each_number in range(0, random.randint(3, 40)):
                random_number = random.randint(0, random.randint(1, 1000))
                random_list.append(random_number)
            sorted_random_list = qs.quicksort(random_list)
            assert len(random_list) == len(sorted_random_list)
            for each_number in range(0, (len(sorted_random_list) - 1)):
                assert (sorted_random_list[each_number]
                        <= sorted_random_list[(each_number + 1)])