示例#1
0
 def test__insertion_sort(self):
     for items in self.generate_cases(self.n_cases):
         ans = sorted(items)
         t1 = time.time_ns()
         sorts.insertion_sort(items)
         self.ts.append(time.time_ns() - t1)
         self.assertEqual(items, ans)
示例#2
0
    def test_is_sorted(self):
        a = int_sort_list[0].copy()
        insertion_sort(a)
        self.assertEqual(a, int_sort_list[1])

        b = str_sort_list[0].copy()
        insertion_sort(b)
        self.assertEqual(b, str_sort_list[1])
示例#3
0
 def test_insertion_sort(self):
     a = [5, 8, 1, 9, 6, 3, 10, 7, 2, 4]
     b = a.copy()
     b.sort()
     insertion_sort(a)
     self.assertEqual(a, b)
     c = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
     d = c.copy()
     d.sort()
     insertion_sort(c)
     self.assertEqual(c, d)
示例#4
0
def test_insertion(array):
    print("Testing insertion sort")
    start = timer()
    insertion_sort(0, len(array), array)
    end = timer()
    time = end - start
    if is_sorted(array):
        print("Sort time is: ", time)
    else:
        print("Not sorted")
    return time
示例#5
0
文件: main.py 项目: Tann1/School
def insertion_timing(input_size, minimum, maximum):
    timings = []

    for size in input_size:
        array = gl.generate_list(size, minimum, maximum)
        time_01 = datetime.now()
        sorts.insertion_sort(array, len(array))
        time_02 = datetime.now()
        time_diff = time_02 - time_01
        timings.append(time_diff)

    return timings
示例#6
0
def test_insertion_selection(array):
    print("Testing insertion/selection combo")
    start = timer()
    insertion_sort(0, len(array)//2, array)
    end = timer()
    first_half = end-start
    start = timer()
    selection_sort(0,len(array), array)
    end = timer()
    second_half = end-start
    time = first_half + second_half
    if is_sorted(array):
        print("Sort time is: ", first_half + second_half)
    else:
        print("Not sorted")
    return time
示例#7
0
def main():
    test_list = [-2.3, 1, 3, 4.2, 4, 2.4, -5.2, 10.9, 11, 3.9]
    shuffle(test_list)
    print("List to sort: ", test_list)
    sorts.insertion_sort(test_list, 0, len(test_list))
    print("\nSorted list by Insertion Sort: ", test_list)
    shuffle(test_list)
    print("\nNew list to sort: ", test_list)
    sorts.quick_sort(test_list, 0, len(test_list) - 1)
    print("\nSorted list by Quick Sort: ", test_list)
    shuffle(test_list)
    print("\nNew list to sort: ", test_list)
    print("\nSorted list by Tree Sort: ", sorts.tree_sort(test_list))
    shuffle(test_list)
    print("\nNew list to sort: ", test_list)
    sorts.pancake_sort(test_list)
    print("\nSorted list by Pancake Sort: ", test_list)
    print()
示例#8
0
    def test_insertion_sort(self):
        # Arrange
        seed = random.randint(0, sys.maxint)
        myRand = random.Random(seed)
        r = 5000
        l = [int(r*myRand.random()) for x in xrange(r)]

        # Act + Assert
        self.assertEqual(sorted(l), insertion_sort(l))
示例#9
0
    def test_insertion_sort(self):

        for test_line in self.test_data:
            insertion_sorted = insertion_sort(list(test_line))
            tim_sorted = sorted(test_line)
            self.assertEqual(
                insertion_sorted, tim_sorted,
                '\n\nFailed to be sorted! The input was:\n{}\n\ninsertion_sort returned:\n{}\n\nand it should be:\n{}\n'
                .format(teal + test_line + NC,
                        red + ''.join(insertion_sorted) + NC,
                        green + ''.join(tim_sorted) + NC))
def main():
   # Make the list to look through, and the target value
   unsorted_list = ["E", "Z", "L", "O", "B", "F"]
   sorted_list = insertion_sort(unsorted_list)
   target_value = "B"

   # Call the search function, catch what it returns
   target_index = binary_search(sorted_list, target_value, 0, 6)

   # Print out our solutions
   print("I found", target_value, "It's at", target_index)
示例#11
0
def data_maker_insertion(liste):
    insertion_sort = open("insertion_sort.txt",
                          "w")  # created the text file here.
    for i in range(
            len(liste)):  # a loop to go over the slices of the original list.
        newList = liste[0:i]
        a = sorts.insertion_sort(newList)
        insertion_sort.write(
            str(a) + "\n")  # writing the counts to the text file line by line
    insertion_sort.close()
    return print("Text file created")
示例#12
0
def sorter(cur, conn, no_parts, part_size):
    for j in range(no_parts):
        cur.execute(
            "CREATE TABLE IF NOT EXISTS SORTED_%s (INDEX INTEGER,VALUE INTEGER)",
            [j])
        cur.execute("SELECT VALUE FROM TEST_%s", [j])
        rows = cur.fetchall()
        sorts = s.insertion_sort(rows)
        for i in range(len(sorts)):
            cur.execute("INSERT INTO SORTED_%s (INDEX,VALUE) VALUES (%s,%s)",
                        (j, i + 1, sorts[i]))

    conn.commit()
def test_insertion_sort(shortlist, longlist, numlist):
    """
    test_insertion_sort will test if the insertion sort function sorted the given list
    parameters:
    'shortlist' The length of the shortest list to test
    'longlist' The length of the longest list to test
    'numlist' The number of lists of each length to test
    eg. test_insertion_sort(5, 10, 9) will test insertion sort of a list size of 5 through 10 and will test 9 lists of each
    """
    for j in range(shortlist, longlist + 1):
        print("Testing Length", j)
        for k in range(numlist):
            print("List Number  ", k + 1)
            createlist = random_list(j)
            print("List Unsorted", createlist)
            sorts.insertion_sort(createlist)
            print("List Sorted  ", createlist)

            if not is_sorted(createlist):
                assert type(error), "Failed to sort"
                print("Error Length", j)
            else:
                print("Success!")
示例#14
0
def bucket_sort(arr: List[int]):
    n = len(arr)
    if n <= 1: return

    minval = maxval = arr[0]
    for i in range(n):
        if arr[i] < minval:
            minval = arr[i]
        elif arr[i] > maxval:
            maxval = arr[i]

    # 以间隔大小10来区分不同值域
    bucket_num = (maxval - minval) // 10 + 1  # 桶的数量
    bucket_arr = [[] for _ in range(bucket_num)]

    for i in range(n):
        k = (arr[i] - minval) // 10  # 需要放入桶的序号 0 - bucket_num-1
        bucket_arr[k].append(arr[i])
        print(k, 'bucket', bucket_arr[k])

    arr.clear()
    for i in bucket_arr:
        insertion_sort(i)
        arr.extend(i)
def binary_search(the_list, target_value):
   """Implements the Binary Search algorithm."""

   # First, sort the list
   sorted_list = insertion_sort(the_list)
   
   # Search for the target value

   # Find length of current segment
   length = len(sorted_list)

   # Initialize start and end variables
   start = 0
   end = length

   # if len >= 1, look for target:
   while length >= 1:
      #  Find the current length and mid point of the segment we're looking in
      mid = start + (length // 2)

      # Determine if middle value is greater or less than, or equal
      # If equal, we've found it, return middle
      if sorted_list[mid] == target_value:
         return (sorted_list, mid)

      # If greater than, reduce segment to left half from middle, repeat loop
      elif sorted_list[mid] > target_value:
         end = mid

      # If less than, reduce segment to right half from middle, repeat loop
      elif sorted_list[mid] < target_value:
         start = mid + 1

      # Reevaluate length before the loop runs again
      length = len(sorted_list[start:end])
         
   # If we can't find the index, return -1
   return (sorted_list, -1)
示例#16
0
 def test_insertion_sort(self):
     numbers = sorts.get_values(20)
     actual = sorts.insertion_sort(numbers)
     expected = sorted(numbers)
     self.assertEqual(expected, actual)
示例#17
0
def main():

    registers_name = read_file_by_name()
    registers_cpf = read_file_by_cpf()

    print("Dados carregados e tratados com sucesso!\n")
    print("O que deseja fazer com o vetor inicial?\n")
    print("1 - Randomizar vetor")
    print("2 - Ordem original do vetor")
    opc = input()
    if (opc == '1'):
        registers_name = random_vector(registers_name)
        registers_cpf = random_vector(registers_cpf)
    print("Qual ordenação deseja fazer?")
    print("1 - Selection Sort")
    print("2 - Insertion Sort")
    print("3 - Bubble Sort")
    opc = input()

    if (opc == '1'):
        print("Ordenar pelo nome ou pelo CPF?")
        print("1 - Nome")
        print("2 - CPF")
        opc = int(input())
        if (opc == 1):
            start = time.time()
            registers_sorted = selection_sort(registers_name)
            end = time.time()
            elapsed_time = end - start
            sucess_menu(elapsed_time, registers_sorted)
        elif (opc == 2):
            start = time.time()
            registers_sorted = selection_sort(registers_cpf)
            end = time.time()
            elapsed_time = end - start
            sucess_menu(elapsed_time, registers_sorted)
        else:
            print("Fim")
            return
    elif (opc == '2'):
        print("Ordenar pelo nome ou pelo CPF?")
        print("1 - Nome")
        print("2 - CPF")
        opc = int(input())
        if (opc == 1):
            start = time.time()
            registers_sorted = insertion_sort(registers_name)
            end = time.time()
            elapsed_time = end - start
            sucess_menu(elapsed_time, registers_sorted)
        elif (opc == 2):
            start = time.time()
            registers_sorted = insertion_sort(registers_cpf)
            end = time.time()
            elapsed_time = end - start
            sucess_menu(elapsed_time, registers_sorted)
        else:
            print("Fim")
            return
    elif (opc == '3'):
        print("Ordenar pelo nome ou pelo CPF?")
        print("1 - Nome")
        print("2 - CPF")
        opc = int(input())
        if (opc == 1):
            start = time.time()
            registers_sorted = bubble(registers_name)
            end = time.time()
            elapsed_time = end - start
            sucess_menu(elapsed_time, registers_sorted)
        elif (opc == 2):
            start = time.time()
            registers_sorted = bubble(registers_cpf)
            end = time.time()
            elapsed_time = end - start
            sucess_menu(elapsed_time, registers_sorted)
        else:
            print("Fim")
            return
示例#18
0
    def test_insertion_sort(self):

        for test_line in self.test_data:
            insertion_sorted = insertion_sort(list(test_line))
            tim_sorted = sorted(test_line)
            self.assertEqual(insertion_sorted, tim_sorted, '\n\nFailed to be sorted! The input was:\n{}\n\ninsertion_sort returned:\n{}\n\nand it should be:\n{}\n'.format(teal + test_line + NC, red + ''.join(insertion_sorted) + NC, green + ''.join(tim_sorted) + NC))
示例#19
0
 def test_insertion_emptyinput(self):
     expected = []
     actual = sorts.insertion_sort([])
     self.assertEqual(expected, actual)
示例#20
0
def main(argv):
    n, A = files.read_lines_of_ints(argv[0])

    print sorts.insertion_sort(A)[0]
from random import randint
import logging
from copy import copy

import sorts

if __name__ == '__main__':

    N_list = [50000]
    ROUND = 1

    logging.basicConfig(level=logging.INFO)

    for N in N_list:
        randint_list = [[randint(0, 2 ** 31 - 1)
                         for _ in range(N)] for _ in range(ROUND)]

        for i in range(ROUND):
            bubble_list = copy(randint_list[i])
            insertion_list = copy(randint_list[i])
            selection_list = copy(randint_list[i])
            quick_list = copy(randint_list[i])
            heap_list = copy(randint_list[i])

            sorts.bubble_sort(bubble_list)
            sorts.insertion_sort(insertion_list)
            sorts.selection_sort(selection_list)
            sorts.quick_sort(quick_list)
            sorts.heap_sort(heap_list)
示例#22
0
def test_insertion_sort():
    test_array = [randint(-10**7, 10000) for i in range(1, 10**2)]
    a = deepcopy(test_array)
    result = insertion_sort(test_array)
    a.sort()
    assert a == result
示例#23
0
#!/usr/bin/env python
from sorts import insertion_sort, merge_sort, heap_sort, build_heap

arr = ['a', 'c', 'b', 'f', 'd', 'aa', 'zzzzzz']
print arr
merge_sort(arr)
print arr

arr = ['a', 'c', 'b', 'f', 'd', 'aa', 'zzzzzz']
print arr
insertion_sort(arr)
print arr

arr = ['a', 'c', 'b', 'f', 'd', 'aa', 'zzzzzz']
print arr
heap_sort(arr)
print arr

arr = ['a', 'c', 'b', 'f', 'd', 'aa', 'zzzzzz']
print arr
build_heap(arr)
print arr
 def do_action(self):
     insertion_sort(self._array)
     self._sorted = '"Insertion sort" used'