Example #1
0
 def test_counting_sort(self):
     A = [2, 5, 3, 0, 2, 3, 0, 3]
     B = []
     for i in range(0, len(A)):
         B.append(0)
     counting_sort(A, B, 5)
     self.assertEqual(B, [0, 0, 2, 2, 3, 3, 3, 5])
     self.assertEqual(A, [2, 5, 3, 0, 2, 3, 0, 3])
Example #2
0
 def test_counting_sort(self):
     A = [2,5,3,0,2,3,0,3]
     B = []
     for i in range(0, len(A)):
         B.append(0)
     counting_sort(A, B, 5)
     self.assertEquals(B, [0,0,2,2,3,3,3,5])
     self.assertEquals(A, [2,5,3,0,2,3,0,3])
Example #3
0
 def test_counting_sort(self):
     from itertools import permutations
     k = 4
     sorted_array = list(range(k + 1))
     for permutation in permutations(sorted_array):
         array = list(permutation)
         counting_sort(array, k)
         self.assertEqual(sorted_array, array)
def test_counting_sort():
    for i in range(500):
        array = []

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

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

        assert array == temp
Example #5
0
def p5ej6(a: List[int]) -> List[int]:
    escaleras = obtener_escaleras(a)
    print("escaleras: " + str(escaleras))
    # Lo ordeno de forma estable por primer digito
    counting_sort(escaleras, key=lambda x: x[0]) # O(n + 9) = O(n)
    print("escaleras sorteadas por primer digito: " + str(escaleras))
    # Lo ordeno por longitud
    escaleras = merge_sort(escaleras, key=lambda x: len(x), inverse=True) # O(n log n)
    print("escaleras sorteadas por longitud: "+ str(escaleras))

    # Concateno los arreglos
    return concat(escaleras)
Example #6
0
def sort_by_frequency(a: List[int]):
    apariciones = armar_apariciones(a)
    print(apariciones)
    apariciones = merge_sort(apariciones, key=lambda x: x[0])
    print(apariciones)
    counting_sort(apariciones, key=lambda x: x[1])
    print(apariciones)

    a_idx = 0
    for (ap, elem) in apariciones:
        for _ in range(ap):
            a[a_idx] = elem
            a_idx += 1
Example #7
0
 def test_counting_sort(self):
     self.assertListEqual(counting_sort([9, 8, 7, 6, 5, 4, 3, 2, 1],
                                        limit=10),
                          [1, 2, 3, 4, 5, 6, 7, 8, 9])
     self.assertListEqual(counting_sort([1, 1, 1, 1, 1],
                                        limit=10),
                          [1, 1, 1, 1, 1])
     self.assertListEqual(counting_sort([7, 0, 1, 7, 7, 1, 1, 3, 6, 0],
                                        limit=10),
                          [0, 0, 1, 1, 1, 3, 6, 7, 7, 7])
     self.assertListEqual(counting_sort([0, 4, 4, 3, 4, 2, 3, 4, 1, 2],
                                        limit=10),
                          [0, 1, 2, 2, 3, 3, 4, 4, 4, 4])
Example #8
0
def radix_sort(a, d):
	'''
		a: list to be sorted, will change to strings
		d: number of digits/letters in each element
	'''
	'''
	** TODO **
	
	- will need a (stable) sort modified specifically to take in
		strings. In python cannot index into type int, so need string
		version of number (i.e. '123' rather than 123)
	- Also needed is a way to store sorted values on i index, and somehow
		keep runtime at Big-Theta(n)

	'''
	not_strings = False
	for i in a:
		if type(i) is str:
			continue
		else:
			not_strings = True
	if not_strings:
		a = list(map(str, a))
	for i in reversed(range(d)):
		# use some stable sort to sort list a on digit i
		# example could be counting sort
		# call sorting algo based on ith digit in each element of a
		# merge_sort(a, 0, len(a))
		b = [0]*len(a)
		a = [str(j)[i] for j in a]
		a = counting_sort(list(map(int, a)), b, 4)
		print(a)
Example #9
0
def radix_sort(arr: [int], max_value: int):
    max_value = max_value if max_value else max(arr)
    num_digits = len(str(max_value))
    for d in range(num_digits):
        arr = counting_sort(
            arr, 10, lambda a: get_digit(a, d + 1)
        )  # we want to use their (d+1)th digit as the key, not the number itself
    return arr
def radix_sort(arr, max_len):
  """
  >>> a = [1,4,2,6,74,2,56,8,39]
  >>> radix_sort(a, 2)
  [1, 2, 2, 4, 6, 8, 39, 56, 74]
  """
  result = arr
  for length in range(1, max_len + 1):
    digit_getter = lambda num: num % pow(10, length) // pow(10, length - 1)
    result = counting_sort(result, digit_getter)

  return result
print('Bubble Sort: ' + str(bubble_sort(lst)))

lst = generate_random_list(100)

print('Selection Sort: ' + str(selection_sort(lst)))

lst = generate_random_list(100)

print('Insertion Sort: ' + str(insertion_sort(lst)))

lst = generate_random_list(100)

print('Merge Sort: ' + str(merge_sort(lst)))

lst = generate_random_list(100)

print('Quick Sort: ' + str(quick_sort(lst)))

lst = generate_random_list(100)

print('Heap Sort: ' + str(heap_sort(lst)))

lst = generate_random_list(100)

print('Counting Sort: ' + str(counting_sort(lst)))

lst = generate_random_list(100)

print('Radix Sort: ' + str(radix_sort(lst)))
if __name__ == "__main__":
    main()

    A = vetor[1:]
    # primeiro elemento da lista eh o tamanho da lista
    n = vetor[0]

    if opt == 'SS':
        saida(selection_sort(A))
    if opt == 'IS':
        saida(insertion_sort(A))
    if opt == 'HS':
        saida(heapsort(A))
    if opt == 'MS':
        saida(topDownMergeSort(A))
    if opt == 'QS':
        saida(quickSort(A))
    if opt == 'CS':
        saida(counting_sort(A))
    if opt == 'RS':
        saida(radix_sort(A))








    
Example #13
0
def compute_medians(e, d, max_e=200):
    medians = [None] * (len(e) - d)
    for i in range(d, len(e)):
        medians[i - d] = counting_sort(e[i - d:i], max_e)[d // 2]
    return medians
Example #14
0
def sort(items, nums=10):
    for i in range(nums - 1, -1, -1):
        items = counting_sort(items, key=lambda item: int(item[i]))

    return items
Example #15
0
        generator = merge_sort(A, 0, len(A) - 1)
        bars = ax.bar(range(len(A)), A, align='edge', color='magenta')
    elif algo == 'heap':
        generator = heap_sort(A)
        bars = ax.bar(range(len(A)), A, align='edge', color='yellow')
    elif algo == 'bubble':
        generator = bubble_sort(A)
        bars = ax.bar(range(len(A)), A, align='edge', color='cyan')
    elif algo == 'insertion':
        generator = insertion(A)
        bars = ax.bar(range(len(A)), A, align='edge', color='black')
    elif algo == 'bucket':
        generator = bucket_sort(A)
        bars = ax.bar(range(len(A)), A, align='edge', color='brown')
    elif algo == 'counting':
        generator = counting_sort(A, B, N + 1)
        bars = ax.bar(range(len(B)), B, align='edge', color='grey')

    title = algo.replace('_', ' ').title()
    ax.set_title(f'{title} sort')
    ax.set_xlim(0, N)
    ax.set_ylim(0, int(1.07 * N))

    iterations = [0]
    text = ax.text(0.02, 0.95, "", transform=ax.transAxes)

    animate = animation.FuncAnimation(fig,
                                      func=update_figure,
                                      fargs=(bars, iterations),
                                      frames=generator,
                                      interval=1,
Example #16
0
 def test_counting_sort(self):
     self.assertEqual([1, 5, 23, 57, 65, 1232],
                      counting_sort([1, 5, 65, 23, 57, 1232]))
     self.assertEqual([-1232, -65, -57, -23, -5, -1],
                      counting_sort([-1, -5, -65, -23, -57, -1232]))
Example #17
0
File: bench.py Project: lbolla/junk
def csort(v):
    return counting_sort(v, len(v), max(v) + 1 if v else None)
import random

for n in [10, 25, 50, 100, 500, 1000, 5000, 10000, 25000]:
    arr = [random.randint(-10000, 10000) for ele in range(n)]
    start_time = time.time()
    result = insertion_sort(arr)
    print('Insertion Sort (n = ' + str(n) + '): ' +
          str(time.time() - start_time) + " seconds")
print("----------------------------------------------------------------------")
for n in [10, 25, 50, 100, 500, 1000, 5000, 10000, 25000, 500000]:
    arr = [random.randint(-10000, 10000) for ele in range(n)]
    start_time = time.time()
    merge_sort(arr, 0, n - 1, inplace=False)
    print('Merge Sort (n = ' + str(n) + '): ' + str(time.time() - start_time) +
          " seconds")
print("----------------------------------------------------------------------")
for n in [10, 25, 50, 100, 500, 1000, 5000, 10000, 25000]:
    arr = [random.randint(-10000, 10000) for ele in range(n)]
    start_time = time.time()
    merge_sort(arr, 0, n - 1, inplace=True)
    print('Merge Sort (Inplace) (n = ' + str(n) + '): ' +
          str(time.time() - start_time) + " seconds")
print("----------------------------------------------------------------------")
for n in [10, 25, 50, 100, 500, 1000, 5000, 10000, 25000]:
    arr = [random.randint(-10000, 10000) for ele in range(n)]
    start_time = time.time()
    result = counting_sort(arr)
    print('Counting Sort (n = ' + str(n) + '): ' +
          str(time.time() - start_time) + " seconds")
print("----------------------------------------------------------------------")
    from insertion import insertion
    from quicksort_module import quicksort
    from merge_module import merge_sort
    import random
    import time
    from matplotlib import pyplot as plt

    n = list(range(10, 50000, 100))
    rand_range = 60000

    times_counting = []
    for i in range(len(n)):
        test_arr = [random.randint(0, rand_range) for x in range(n[i])]
        sorted_arr = [0 for x in range(n[i])]
        start = time.time()
        counting_sort(test_arr, sorted_arr, rand_range)
        end = time.time()
        times_counting.append(end - start)
        print(n[i])

    times_bucket = []
    for i in range(len(n)):
        test_arr = [random.randint(0, rand_range) for x in range(n[i])]
        start = time.time()
        bucket_sort(test_arr)
        end = time.time()
        times_bucket.append(end - start)
        print(n[i])

    times_merge = []
    for i in range(len(n)):
Example #20
0
 def test_counting_sort_already_sorted(self):
     A = sorted([randint(0, 100) for _ in range(30)])
     B = A.copy()
     C = counting_sort(B)
     self.assertEqual(A, C)
Example #21
0
 def test_counting_sort(self):
     self.assertEquals(counting_sort(self.test_list[2], 23), self.res_list[2])
     self.assertEquals(counting_sort(self.test_list[3], 11), self.res_list[3])
Example #22
0
 def test_counting_sort(self):
     A = [randint(0, 100) for _ in range(30)]
     B = A.copy()
     A.sort()
     C = counting_sort(B)
     self.assertEqual(A, C)
# Driver code for testing
# counting sort code
# Numbers are arbitrary
# Can be changed

from random import randint
from counting_sort import counting_sort

n = randint(5, 20)

highest = 0

array = []

for i in range(n):
    tmp = randint(0, 100)

    if tmp > highest:
        highest = tmp

    array.append(tmp)

print(array)
print(counting_sort(array, highest))
Example #24
0
def main():
  array = [0,1,2,4,1,2,7,4,12,5,2,7,0,1,8]
  newArray = counting_sort(array)
  print("Array original   % s" % list(map(str, array)))
  print("Array organizado % s" % list(map(str, newArray)))
Example #25
0
def counting_sort_test():
    arr = [[4, 5, 6], [1, 2, 3], [11, 23, 45]]

    counting_sort(arr, key=lambda x: x[0])

    print(arr)
    start = time.time()
    heapsort(HS)
    tempo['HS'] = (time.time() - start)*1000

    start = time.time()
    quickSort(QS)
    tempo['QS'] = (time.time() - start)*1000

    start = time.time()
    topDownMergeSort(MS)
    tempo['MS'] = (time.time() - start)*1000

    start = time.time()
    CS, menorValor = entrada_NegaToPosi(CS, n)    # deixa lista totalmente positiva
    CS = counting_sort(CS)
    CS = entrada_PosiToNega(CS, menorValor, n)    # retorna a lista com valores original
    tempo['CS'] = (time.time() - start)*1000

    start = time.time()
    RS, menorValor = entrada_NegaToPosi(RS, n) # deixa lista totalmente positiva
    RS = radix_sort(RS)
    RS = entrada_PosiToNega(RS, menorValor, n) # retorna a lista com valores original
    tempo['RS'] = (time.time() - start)*1000

    print "{}".format(tempo)

    plot_dicionario(tempo, n)


__email__ = "*****@*****.**"

from counting_sort import counting_sort
from counting_sort_complex import counting_sort_complex
from bucket_sort import bucket_sort
from radix_sort import radix_sort_int, radix_sort_str
import random

if __name__ == '__main__':
    listSize = 100
    bigList = [random.randint(0, listSize) for i in xrange(listSize)]

    print "Finished creating .."

    # Test all sorting
    print counting_sort(bigList)
    print counting_sort_complex(bigList)
    print bucket_sort(bigList)
    print radix_sort_int(bigList)

    # convert numbers to String so we can use radix-sort directly on words.
    stringList = []
    maxWordSize = 15
    for i in range(listSize):
        word = ""
        for j in range(maxWordSize):
            if random.randint(0,10) <= 4:
                word += chr(random.randint(48,91))
        stringList.append(word)

    print radix_sort_str(stringList)
Example #28
0
    if choice == 1:
        choiceStr = "insertion sort"
        insertion_sort(integers)
    elif choice == 2:
        choiceStr = "merge sort"
        p = 0
        r = len(integers)
        merge_sort(integers, p, r - 1)
    elif choice == 3:
        choiceStr = "heap sort"
        heap_sort(integers)
    elif choice == 4:
        choiceStr = "quick sort"
        quick_sort(integers, 0, len(integers) - 1)
    elif choice == 5:
        choiceStr = "counting sort"
        integers = counting_sort(integers, len(integers))
    elif choice == 6:
        choiceStr = "default sort(timsort - a hybrid of merge and insertion)"
        integers = sorted(integers)
    else:
        choiceStr = "no such sort"

    after = time.time()
    timediff = round(float(after - before), 2)
    if sorted(integers) == integers:
        print "Python = ", choiceStr, ", sorted ", meaningfulArrayLength(
            len(integers)), " numbers in ", timediff, " seconds"
    else:
        print "DID NOT SORT CORRECTLY"
Example #29
0
def test1():
    A = [random.randint(0, 99999) for i in range(100000)]
    counting_sort(A)
Example #30
0
'''
This is the official implementation for all the problems for every assignment given in question
'''

import counting_sort as cs
import bucket_sort as bs
import sort_words as sw
import holerith_sorting as hs

# For problem 1.a
print("Couting sort", cs.counting_sort([9, 1, 6, 7, 6, 2, 1]))

#For problem 1.b
print("Bucket sort", bs.bucket_sort([0.9, 0.1, 0.6, 0.7, 0.6, 0.3, 0.1]))

# For problem 1.d
print(
    "Word sort",
    sw.word_sort([
        "word", "category", "cat", "new", "news", "world", "bear", "at",
        "work", "time"
    ]))

# For problem 2.a
arr = [6, 7, 4, 333, 22, 23, 21, 444, 123, 1233, 1123, 1, 0, 12, 440, 11, 1233]
sorter = hs.Sort(arr)
print("Holerith sort", sorter.radix_sort())
#!/usr/bin/python

from counting_sort import counting_sort
import random
import time

if __name__ == '__main__':
    start = time.time()

    a = [random.randint(0,i) for i in range(10,100000)]

    middle = time.time()
    print "time for building %d array: %f" % (len(a), middle - start)

    counting_sort(a, max(a))
    time_qsort = time.time()
    print "time for qsort: %f" % (time_qsort - middle)

Example #32
0
nlist = [9, 12, 98, 17, 22, 3]
selection_sort.selectionsort(nlist)
print(nlist)

# how to use merge sort
# give nlist as an input list to sort
nlist = [23, 88, 98, 99, 12, 18, 71, 4]
merge_sort.mergesort(nlist)
print(nlist)

# how to use insertion sort
# give 'data' as an input list to sort
data = [3, 8, 12, 98, 92, 64, 23, 10]
insertion_sort.insertion(data)
print(data)

# how to use counting sort
# give nlist as an input list to sort
# and an integer to set it as maximum value
nlist = [1, 4, 1, 2, 2, 5, 2]
max_value = 7
counting_sort.counting_sort(nlist, max_value)
print(nlist)

# how to use bubble sort
# give nlist as an input list to sort
# remember that this bubble sort is sorting value from the biggest one to the lowest
nlist = [71, 66, 28, 83, 90, 10]
bubble_sort.bubble_sort(nlist)
print(nlist)
__email__ = "*****@*****.**"

from counting_sort import counting_sort
from counting_sort_complex import counting_sort_complex
from bucket_sort import bucket_sort
from radix_sort import radix_sort_int, radix_sort_str
import random

if __name__ == '__main__':
    listSize = 100
    bigList = [random.randint(0, listSize) for i in xrange(listSize)]

    print "Finished creating .."

    # Test all sorting
    print counting_sort(bigList)
    print counting_sort_complex(bigList)
    print bucket_sort(bigList)
    print radix_sort_int(bigList)

    # convert numbers to String so we can use radix-sort directly on words.
    stringList = []
    maxWordSize = 15
    for i in range(listSize):
        word = ""
        for j in range(maxWordSize):
            if random.randint(0, 10) <= 4:
                word += chr(random.randint(48, 91))
        stringList.append(word)

    print radix_sort_str(stringList)
Example #34
0
 def test_counting_sort_3(self):
     lst = create_random_int_list(1000, 1000)
     self.assertEqual(counting_sort.counting_sort(lst), sorted(lst))
Example #35
0
 def test_counting_sort_1(self):
     lst = [0, 21, 15, 10, 8, 5]
     exp = [0, 5, 8, 10, 15, 21]
     self.assertEqual(counting_sort.counting_sort(lst), exp)
Example #36
0
def string_radix_sort(A, d):
    """Perform a radix sort on a list A of uppercase strings of length d"""
    for i in reversed(range(0, d)):
        A = counting_sort(A, 26, lambda s: ord(s[i]) - 65)

    return A
Example #37
0
def radix_sort(l, k):
    for i in range(k):
        key_func = lambda x: int(x / (10**i)) % 10
        l = counting_sort(l, 10, key_func)
        print(l)
    return l
Example #38
0
def main():
    arr = "ZYXWVUTSRQPONMLKJIHGFEDCBA"
    ans = counting_sort(arr)
    print("Sorted character array is % s" % ("".join(ans)))