Пример #1
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 task2():
    for i in range(7, 21):
        lst = [i for i in range(2**i)]
        print(lst)

        start = time.time()
        insertion_op = insertion.insertion(lst)[1]
        end = time.time()
        insertion_time = end - start

        start = time.time()
        selection_op = selection.selection(lst)[1]
        end = time.time()
        selection_time = end - start

        start = time.time()
        shell_op = shellsort.shell(lst)[1]
        end = time.time()
        shell_time = end - start

        with open("task2_op_2.csv", 'a') as file:
            results_writer = csv.writer(file, delimiter=',')
            results_writer.writerow(['{}'.format(i)] +
                                    ['{}'.format(selection_op)] +
                                    ['{}'.format(insertion_op)] +
                                    ['{}'.format(shell_op)])

        with open("task2_time_2.csv", 'a') as file:
            results_writer = csv.writer(file, delimiter=',')
            results_writer.writerow(['{}'.format(i)] +
                                    ['{}'.format(selection_time)] +
                                    ['{}'.format(insertion_time)] +
                                    ['{}'.format(shell_time)])
Пример #3
0
def timsort(arr):
    runs, sorted_runs = [], []
    length = len(arr)
    if length == 0:
        return arr
    new_run = [arr[0]]

    for i in range(1, length):

        if i == length - 1:
            new_run.append(arr[i])
            runs.append(new_run)
            break
        if arr[i] < arr[i - 1]:
            if new_run is None:
                runs.append(new_run)
                new_run = []
            else:
                runs.append([arr[i]])
                new_run.append(arr[i])

        else:
            new_run.append(arr[i])

    for collection in runs:
        sorted_runs.append(insertion(collection))

    sorted_array = []
    for run in sorted_runs:
        sorted_array = merge(sorted_array, run)

    return sorted_array
Пример #4
0
def shell(arr: list, k: int = 1) -> list:
    L = len(arr)
    d = L // (2**k)
    shells = list()
    i = 0
    n = 0

    while True:
        shells.append([])
        while True:
            shells[-1].append(d * n + i)
            n += 1
            if d * n + i >= L:
                n = 0
                i += 1
                break
        if d * n + i >= d:
            break

    for sh in shells:
        temp = [arr[s] for s in sh]
        temp = insertion.insertion(temp)
        for i, s in enumerate(sh):
            arr[s] = temp[i]

    if L // (2**k + 1) > 1:
        arr = shell(arr, k + 1)

    return arr
Пример #5
0
def bucket(raw):
    bucket = {}
    i = 0
    while(i < len(raw)):
        k = raw[i]/100
        if bucket.has_key(k):
            bucket[k].append(raw[i])
        else:
            bucket[k] = [raw[i]]
        i+=1
    i = 0
    for k in bucket:
        curr = bucket[k]
        insertion(curr)
        for n in curr:
            raw[i] = n
            i+=1
Пример #6
0
 def select_pivots(pivot_list, p, n):
     pi = int(p/(n**2))
     if not pi:
         pi = 1
     pivot_src = insertion(pivot_list)
     pivots = [pivot_src[pi+p*x] for x in range(p)]
     pivots = pivots[1:]
     return pivots
Пример #7
0
def shell(st):
  nums = st.split(' ')
  #print nums
  num = 0
  original = []
  step =[7,3,1]
  mul = 0 
  sublist = []

  mulp = 0 


  length=len(nums)
  for i in nums:
  	original.append(int(i))

  #print original

  ## first go through 7, and 3 and 1. 
  for s in step: 
    for i in range(length):
      mul = 0
      #print "i is", i
      position = i + s * mul
      sublist =[]
      while position < length:
        #print "position is", position
        sublist.append(str(original[position]))
        mul += 1
        position = i + s * mul

      
      if len(sublist) < 2:
          sublist=[]
          break
      else: 
        #print "sublist", sublist
        al=' '.join(sublist)
        #print "before insertion is", al
        sublist=insertion.insertion(al)
        al = ''
        #Sprint "sublist after i is", sublist
        mul=0
        position = i + s * mul
        while position < length and mul < len(sublist):
          original[position] = sublist[mul]
          mul += 1
          position = i + s * mul
        #print "after it is", original

      mulp += 1
      sublist=[]
      




  print original
Пример #8
0
def time(a, sortname):
    import time
    from selection import selection
    from insertion import insertion
    from merge import mergeSort
    from quick import quickSort
    from heap import heapSort
    time_start = time.time()
    if sortname == 'Selection':
        selection(a)
    if sortname == 'Insertion':
        insertion(a)
    if sortname == 'Merge':
        mergeSort(a)
    if sortname == 'Quick':
        quickSort(a)
    if sortname == 'Heap':
        heapSort(a)
    time_end = time.time()
    return (time_end - time_start)
Пример #9
0
def bucket(arr :list) -> list:
  M = max(arr)
  L = 10
  buck = [[] for _ in range(L+1)]

  for i in arr:
    buck[int(L * i/M)].append(i)

  for i, v in enumerate(buck):
    buck[i] = insertion.insertion(v)

  rv = list()
  for b in buck:
    rv.extend(b)

  return rv
def task4():
    for i in range(7, 21):
        lst = [random.randint(1, 3) for i in range(2**i)]
        selection_time = 0
        insertion_time = 0
        shell_time = 0

        selection_op = 0
        insertion_op = 0
        shell_op = 0
        for j in range(10):
            random.shuffle(lst)
            print(j, lst)

            start = time.time()
            insertion_op += insertion.insertion(copy.deepcopy(lst))[1]
            end = time.time()
            insertion_time += end - start

            start = time.time()
            selection_op += selection.selection(copy.deepcopy(lst))[1]
            end = time.time()
            selection_time += end - start

            start = time.time()
            shell_op += shellsort.shell(copy.deepcopy(lst))[1]
            end = time.time()
            shell_time += end - start

        with open("task4_op_2.csv", 'a') as file:
            results_writer = csv.writer(file, delimiter=',')
            results_writer.writerow(['{}'.format(i)] +
                                    ['{}'.format(int(selection_op / 10))] +
                                    ['{}'.format(int(insertion_op / 10))] +
                                    ['{}'.format(int(shell_op / 10))])

        with open("task4_time_2.csv", 'a') as file:
            results_writer = csv.writer(file, delimiter=',')
            results_writer.writerow(['{}'.format(i)] +
                                    ['{}'.format(selection_time / 10)] +
                                    ['{}'.format(insertion_time / 10)] +
                                    ['{}'.format(shell_time / 10)])
Пример #11
0
def time_pythonsort(l):
    start = time.time()
    insertion.insertion(l)
    return time.time() - start
Пример #12
0
def time_insertion(l):
    start = time.time()
    insertion.insertion(l)
    return time.time() - start
Пример #13
0
 def test_insertion(self):
     self.assertEquals(insertion(0b10000000000, 0b10011, 2, 6), 0b10001001100)
Пример #14
0
def test_negative_values():
    lst = [8,4,23,-42,16,-15]
    expected = [-42,-15,4,8,16,23]
    actual = insertion(lst)
    assert actual == expected
Пример #15
0
        generator = quicksort(A, 0, len(A) - 1)
        bars = ax.bar(range(len(A)), A, align='edge', color='red')
    elif algo == 'randomized_quick':
        generator = randomized_quicksort(A, 0, len(A) - 1)
        bars = ax.bar(range(len(A)), A, align='edge', color='orange')
    elif algo == 'merge':
        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)
Пример #16
0
sys.path.insert(0, 'sorting')

nums = numpy.random.randint(100, size=20).tolist()
sortedNums = sorted(nums)

try:
    from bubble import bubble
    if (bubble(list(nums)) == sortedNums):
        print "bubblesort success!"
    else:
        print "bubblesort incorrect."
except:
    print "bubblesort function errored or is incomplete."
try:
    from insertion import insertion
    if (insertion(list(nums)) == sortedNums):
        print "insertionsort success!"
    else:
        print "insertionsort incorrect."
except:
    print "insertionsort function errored or is incomplete."
try:
    from merge import mergesort
    if (mergesort(list(nums)) == sortedNums):
        print "mergesort success!"
    else:
        print "mergesort incorrect."
except:
    print "mergesort function errored or is incomplete."
try:
    from quick import quick
Пример #17
0
 def pivot3rand(l, r):
     pivotindexes = [random.randint(l, r) for _ in range(3)]
     pivots = [list_arg_internal[x] for x in pivotindexes]
     piv_dict = dict(zip(pivots, pivotindexes)).copy()
     pivots = insertion(pivots)
     return piv_dict[pivots[1]]
Пример #18
0
def test_unique_values():
    lst = [8,4,23,42,16,15]
    expected = [4,8,15,16,23,42]
    actual = insertion(lst)
    assert actual == expected
    inorder(root.left)
    print(root.val)
    inorder(root.right)


# PreOrder teaversal
def PreOrder(root):
    if root == None:
        return
    print(root.val)
    PreOrder(root.left)
    PreOrder(root.right)


# PostOrder teaversal
def PostOrder(root):
    if root == None:
        return
    PostOrder(root.left)
    PostOrder(root.right)
    print(root.val)


if __name__ == "__main__":
    root = insertion()
    print("Inorder traversal")
    inorder(root)
    print("Preorder traversal")
    PreOrder(root)
    print("post order traversal")
    PostOrder(root)
Пример #20
0
def test_duplicate_value():
    lst = [8,4,23,42,16,15,8,23]
    expected = [4,8,8,15,16,23,23,42]
    actual = insertion(lst)
    assert actual == expected
    start_b = time.time()
    sorted_bubble = bubble.bubble(before)
    print(sorted_bubble)
    end_b = time.time()
    print('bubble', end_b - start_b)

    # selection
    start_s = time.time()
    sorted_selection = selection.selection(before)
    print(sorted_selection)
    end_s = time.time()
    print('selection', end_s - start_s)

    # insertion
    start_i = time.time()
    sorted_insertion = insertion.insertion(before)
    print(sorted_insertion)
    end_i = time.time()
    print('insertion', end_i - start_i)

    # quick
    start_q = time.time()
    sorted_quick = quick.quick(before)
    print(sorted_quick)
    end_q = time.time()
    print('quick', end_q - start_q)

    # merge
    start_m = time.time()
    sorted_merge = merge_sort.devide(before)
    print(sorted_merge)
Пример #22
0
while looper:

    menu_choice = inputOutput.menu()  #Gets menu choice

    #Bubble Sort
    if menu_choice == "1":
        data_chosen = inputOutput.input_to_choose()
        print("Performing Bubble Sort")
        output = bubble.bubble(data_chosen)
        inputOutput.output_list(output)

    #Insertion Sort
    elif menu_choice == "2":
        data_chosen = inputOutput.input_to_choose()
        print("Performing Insertion Sort")
        output = insertion.insertion(data_chosen)
        inputOutput.output_list(output)

    # Merge Sort
    elif menu_choice == "3":
        data_chosen = inputOutput.input_to_choose()
        print("Performing Merge Sort")
        output = merge.merge_sort(data_chosen)
        inputOutput.output_list(output)

    # Quick Sort
    elif menu_choice == "4":
        data_chosen = inputOutput.input_to_choose()
        print("Performing Quick Sort")
        output = quick.quick_sort(data_chosen)
        inputOutput.output_list(output)