コード例 #1
0
def callInsertionSort(list):
    start_time = time.time()
    insertion_sort.insertionSort(list)
    insertionSort_time = (time.time() - start_time)
    print("\nInsertion Sort --- %s  ---\n" % insertionSort_time)
    #print(list)
    print("\n")
コード例 #2
0
def bucketSort(myList, bucketSize=DEFAULT_BUCKET_SIZE):
    if (len(myList) == 0):
        print('You don\'t have any elements in array!')

    minValue = myList[0]
    maxValue = myList[0]

    # For finding minimum and maximum values
    for i in range(0, len(myList)):
        if myList[i] < minValue:
            minValue = myList[i]
        elif myList[i] > maxValue:
            maxValue = myList[i]

    # Initialize buckets
    bucketCount = math.floor((maxValue - minValue) / bucketSize) + 1
    buckets = []
    for i in range(0, bucketCount):
        buckets.append([])

    # For putting values in buckets
    for i in range(0, len(myList)):
        buckets[math.floor(
            (myList[i] - minValue) / bucketSize)].append(myList[i])

    # Sort buckets and place back into input array
    sortedArray = []
    for i in range(0, len(buckets)):
        insertionSort(buckets[i])
        for j in range(0, len(buckets[i])):
            sortedArray.append(buckets[i][j])

    return sortedArray
コード例 #3
0
def bucketSort(numbers):
    length = len(numbers)
    buckets = [[] for _ in range(length)]
    for n in numbers:
        buckets[n // length].append(n)
    for b in buckets:
        if b:
            insertionSort(b)
    numbers = np.array([num for bucket in buckets for num in bucket])
    return numbers
コード例 #4
0
def start():
    global data

    if var.get() == OptionList[0]:
        bub_sort(data, drawdata, speed.get())
    if var.get() == OptionList[1]:
        mergeSort(data, 0, int(data_size.get()) - 1, drawdata, speed.get())
    if var.get() == OptionList[2]:
        insertionSort(data, drawdata, speed.get())
    if var.get() == OptionList[3]:
        quickSort(data, 0, int(data_size.get()) - 1, drawdata, speed.get())
コード例 #5
0
def methodTester(sortMethod, baseSize=10):

    #store the sorted file names
    sorted_files = []

    # Create the random number files
    files = _fileCreator(baseSize)

    # Create the time table file
    timing_file = open(str(sortMethod) + "Sort_test_times", 'w')
    timing_file.write("Input Size (n):	Time cost:")

    # For each of the files:
    for file in files:

        # Create a list from the numbers stored in the file
        number_list = _fileToList(file)
        number_count = len(number_list)
        for i in range(number_count):
            number_list[i] = float(number_list[i])

        # Create the file to store the sorted list
        sortedFileName = str(file) + "_" + sortMethod + "sort_sorted"
        sorted_files.append(sortedFileName)
        sortedFile = open(sortedFileName, 'w')

        # Check sorting method, then sort while timing
        if sortMethod == 'merge':
            start_time = time.time()
            numberListSorted = mSort.mergeSort(number_list, 1,
                                               len(number_list))
            stop_time = time.time()
        elif sortMethod == 'quick':
            start_time = time.time()
            numberListSorted = qSort.quickSort(number_list, 0,
                                               len(number_list) - 1)
            stop_time = time.time()
        elif sortMethod == 'insertion':
            start_time = time.time()
            numberListSorted = iSort.insertionSort(number_list,
                                                   len(number_list))
            stop_time = time.time()
        else:
            print('''Uh oh, the provided sort method has yet to be implemented!
Please use either 'merge', 'quick', or 'insertion'.\n''')

        # Store the sorted list in its respective file
        sortedFile.write(str(numberListSorted))
        sortedFile.close()

        # Calculate the time taken, then add it to the timing file
        sort_time = stop_time - start_time
        timing_file.write("\n" + str(number_count) + "		" + str(sort_time))

    # Close the timing file, and prompt the user on whether
    #  or not to delete the created files used to calculate
    #  the timing data.
    timing_file.close()
    files.extend(sorted_files)
    _askDelete(files)
コード例 #6
0
 def test_large_inputs(self):
     print("Testing large inputs...")
     random_list = random.sample(range(-800000, 800000), 10000)
     sorted_random_list = sorted(random_list)
     self.assertEqual(bubbleSort(random_list), sorted_random_list)
     self.assertEqual(insertionSort(random_list), sorted_random_list)
     self.assertEqual(selectionSort(random_list), sorted_random_list)
コード例 #7
0
def compare_merge_insert():
    N = 10**4  # change here to change array size. 10**4 is enough big, it takes about 5 seconds.
    arr_insert = [random.randint(0, 10**6) for _ in range(N)]
    arr_merge = copy.deepcopy(arr_insert)
    start_time = time.time()
    insertion_sort.insertionSort(arr_insert)
    insert_time = time.time() - start_time
    start_time = time.time()
    merge_sort.mergeSort(arr_merge)
    merge_time = time.time() - start_time

    # check error
    for i, n in enumerate(arr_insert):
        if n != arr_merge[i]:
            print("Error: result is not the same!, ", i)
            return
    print("result is the same")
    print("insert sort time = ", insert_time)
    print("merge  sort time = ", merge_time)
コード例 #8
0
def analyze_text(book, text):
    '''Performs a very naive analysis of the words in the text, returning the SORTED list of WordData items'''
    # lowercase the entire text
    with open(text, 'r') as f:
        all_words = f.read()
        all_words = all_words.lower()

    # split the text by whitespace to get a list of words
    string_file = re.split('\s+', all_words)
    words = []

    for i in string_file:
        new_i = re.findall("[a-z]+", i)
        if len(new_i) > 1:

            # convert each word to the longest run of characters
            if len(new_i[0]) >= len(new_i[1]):
                del new_i[1]
            else:
                del new_i[0]

        # eliminate any words that are empty after conversion to characters
        if new_i:
            words.append(new_i)

    # count up the occurance of each word into a dictionary of: word -> count
    agg_words = {}
    for w in words:
        if w[0] in agg_words:
            temp_count = agg_words[w[0]]
            temp_count += 1
            agg_words[w[0]] = temp_count
        else:
            agg_words[w[0]] = 1

    # create a WordData item for each word in our list of words
    word_objects = []

    for key in agg_words:
        # percent needs to be stored rounded to 1 decimal or the printing doesn't work correctly
        wordData = WordData(book, key, agg_words[key],
                            round(agg_words[key] / len(words) * 100, 1))
        word_objects.append(wordData)

    # sort the WordData list using Bubble Sort, Insertion Sort, or Selection Sort:
    # 1. highest percentage [descending]
    # 2. highest count (if percentages are equal) [descending]
    # 3. lowest alpha order (if percentages and count are equal) [ascending]

    # sorted_words = bubbleSort(word_objects)
    sorted_words = insertionSort(word_objects)
    # sorted_words = selectionSort(word_objects)

    return sorted_words
コード例 #9
0
def bucketSort(Arr):
    max_value = max(Arr)
    size = max_value / len(Arr)
    buckets_list = []

    for x in range(len(Arr)):  # create buckets
        buckets_list.append([])

    for y in range(len(Arr)):
        z = int(Arr[y] / size)
        if (z != len(Arr)):
            buckets_list[z].append(Arr[y])
        else:
            buckets_list[len(Arr) - 1].append(Arr[y])

    for z in range(len(Arr)):  # use previously implemented insertion sort
        iSort.insertionSort(buckets_list[z])

    Arr_out = []
    for x in range(len(Arr)):  # combine buckets into final output
        Arr_out = Arr_out + buckets_list[x]
    return Arr_out
コード例 #10
0
def drawAllGraph():
    insertionTimes = []  #[0.0, 0.03, 9.9, 29.86] #10**k for k = 1,3,6,9
    selectionTimes = []
    mergeTimes = []  #[0.0, 0.0, 5.33, 29.9 ]
    arraySizes = [10**i for i in range(1, 5)]

    for i in arraySizes:
        randomList = np.random.random_integers(1, 10000000, size=i)

        startTime = time.time()
        sel_list = selection_sort.selectionSort(
            np.random.random_integers(1, 10000000, size=i))
        runTime = time.time() - startTime
        selectionTimes.append(runTime)

        startTime = time.time()
        merge_list = MERGE.mergeSort(
            np.random.random_integers(1, 10000000, size=i))
        runTime = time.time() - startTime
        mergeTimes.append(runTime)

        startTime = time.time()
        insertion_list = insertion_sort.insertionSort(
            np.random.random_integers(1, 10000000, size=i))
        runTime = time.time() - startTime
        insertionTimes.append(runTime)

    plt.figure(figsize=(12, 5))
    plt.plot(arraySizes,
             selectionTimes,
             marker='x',
             c='b',
             label='Selectionsort')
    plt.plot(arraySizes, mergeTimes, marker='x', c='r', label='Mergesort')
    plt.plot(arraySizes,
             insertionTimes,
             marker='x',
             c='g',
             label='Insertionsort')
    plt.xscale('log')
    plt.yscale('log')
    plt.xlabel("size of unsorted list - log scale")
    plt.ylabel("seconds of computation - log scale")
    plt.legend(loc=2)
    plt.grid()
    plt.title("Selectionsort vs Mergesort vs Insertionsort")
    plt.show()


#http://nixonite.github.io/posts/complexity-of-algorithms-with-python.html
コード例 #11
0
ファイル: bucket_sort.py プロジェクト: IsmailMarghich/Courses
def bucketSort(customList):
    numberofBuckets = round(math.sqrt(len(customList)))
    maxValue = max(customList)
    arr = []

    for i in range(numberofBuckets):
        arr.append([])
    for j in customList:
        index_b = math.ceil(j * numberofBuckets / maxValue)
        arr[index_b - 1].append(j)

    for i in range(numberofBuckets):
        arr[i] = sort.insertionSort(arr[i])

    k = 0
    for i in range(numberofBuckets):
        for j in range(len(arr[i])):
            customList[k] = arr[i][j]
            k += 1
    return customList
コード例 #12
0
 def test_empty_input(self):
     print("Testing edge cases...")
     self.assertEqual(bubbleSort([]), [])
     self.assertEqual(insertionSort([]), [])
     self.assertEqual(selectionSort([]), [])
コード例 #13
0
    def test_insertionSort_array_last_val(self):
        words = self.test_create_WordData_array()
        sorted_words = insertionSort(words)

        self.assertEqual(sorted_words[7].word, 'm')
コード例 #14
0
    def test_nativeSort_fail(self):
        arr = self.test_create_array()
        sorted_arr = insertionSort(arr)

        self.assertEqual(sorted_arr[7], 1)
コード例 #15
0
    def test_insertionSort_array_last_val(self):
        arr = self.test_create_array()
        sorted_arr = insertionSort(arr)

        self.assertEqual(sorted_arr[3], 2)
コード例 #16
0
 def testInsertionSort_repeatedValues_sorts(self):
     A = [2, 3, 4, 3, 2, 3, 1]  # Example from CLRS p.18 3rd ed.
     sort.insertionSort(A)
     self.assertEquals(A, [1, 2, 2, 3, 3, 3, 4])
コード例 #17
0
 def testInsertionSort_stringInput_sorts(self):
     A = ['e', 'b', 'd', 'f', 'a', 'c']
     sort.insertionSort(A)
     self.assertEquals(A, ['a', 'b', 'c', 'd', 'e', 'f'])
コード例 #18
0
 def testInsertionSort_integerInput_sorts(self):
     A = [5, 2, 4, 6, 1, 3]  # Example from CLRS p.18 3rd ed.
     sort.insertionSort(A)
     self.assertEquals(A, [1, 2, 3, 4, 5, 6])
コード例 #19
0
 def testInsertionSort_sizeOnearray_isNoop(self):
     A = [42]
     sort.insertionSort(A)
     self.assertEquals(A, [42])
コード例 #20
0
 def test_insertionSort(self):
     self.assertEqual(insertionSort([8, 5, 2, 9, 5, 6, 3]),
                      [2, 3, 5, 5, 6, 8, 9])
     self.assertEqual(insertionSort([1]), [1])
     self.assertEqual(insertionSort([1, 2]), [1, 2])
     self.assertEqual(insertionSort([2, 1]), [1, 2])
     self.assertEqual(insertionSort([1, 3, 2]), [1, 2, 3])
     self.assertEqual(insertionSort([3, 1, 2]), [1, 2, 3])
     self.assertEqual(insertionSort([1, 2, 3]), [1, 2, 3])
     self.assertEqual(
         insertionSort([
             -4, 5, 10, 8, -10, -6, -4, -2, -5, 3, 5, -4, -5, -1, 1, 6, -7,
             -6, -7, 8
         ]), [
             -10, -7, -7, -6, -6, -5, -5, -4, -4, -4, -2, -1, 1, 3, 5, 5, 6,
             8, 8, 10
         ])
     self.assertEqual(
         insertionSort([
             -7, 2, 3, 8, -10, 4, -6, -10, -2, -7, 10, 5, 2, 9, -9, -5, 3, 8
         ]),
         [-10, -10, -9, -7, -7, -6, -5, -2, 2, 2, 3, 3, 4, 5, 8, 8, 9, 10])
     self.assertEqual(
         insertionSort([
             8, -6, 7, 10, 8, -1, 6, 2, 4, -5, 1, 10, 8, -10, -9, -10, 8, 9,
             -2, 7, -2, 4
         ]), [
             -10, -10, -9, -6, -5, -2, -2, -1, 1, 2, 4, 4, 6, 7, 7, 8, 8, 8,
             8, 9, 10, 10
         ])
     self.assertEqual(
         insertionSort([5, -2, 2, -8, 3, -10, -6, -1, 2, -2, 9, 1, 1]),
         [-10, -8, -6, -2, -2, -1, 1, 1, 2, 2, 3, 5, 9])
     self.assertEqual(
         insertionSort([
             2, -2, -6, -10, 10, 4, -8, -1, -8, -4, 7, -4, 0, 9, -9, 0, -9,
             -9, 8, 1, -4, 4, 8, 5, 1, 5, 0, 0, 2, -10
         ]), [
             -10, -10, -9, -9, -9, -8, -8, -6, -4, -4, -4, -2, -1, 0, 0, 0,
             0, 1, 1, 2, 2, 4, 4, 5, 5, 7, 8, 8, 9, 10
         ])
     self.assertEqual(
         insertionSort([
             4, 1, 5, 0, -9, -3, -3, 9, 3, -4, -9, 8, 1, -3, -7, -4, -9, -1,
             -7, -2, -7, 4
         ]), [
             -9, -9, -9, -7, -7, -7, -4, -4, -3, -3, -3, -2, -1, 0, 1, 1, 3,
             4, 4, 5, 8, 9
         ])
     self.assertEqual(
         insertionSort([
             427, 787, 222, 996, -359, -614, 246, 230, 107, -706, 568, 9,
             -246, 12, -764, -212, -484, 603, 934, -848, -646, -991, 661,
             -32, -348, -474, -439, -56, 507, 736, 635, -171, -215, 564,
             -710, 710, 565, 892, 970, -755, 55, 821, -3, -153, 240, -160,
             -610, -583, -27, 131
         ]), [
             -991, -848, -764, -755, -710, -706, -646, -614, -610, -583,
             -484, -474, -439, -359, -348, -246, -215, -212, -171, -160,
             -153, -56, -32, -27, -3, 9, 12, 55, 107, 131, 222, 230, 240,
             246, 427, 507, 564, 565, 568, 603, 635, 661, 710, 736, 787,
             821, 892, 934, 970, 996
         ])
     self.assertEqual(
         insertionSort([
             991, -731, -882, 100, 280, -43, 432, 771, -581, 180, -382,
             -998, 847, 80, -220, 680, 769, -75, -817, 366, 956, 749, 471,
             228, -435, -269, 652, -331, -387, -657, -255, 382, -216, -6,
             -163, -681, 980, 913, -169, 972, -523, 354, 747, 805, 382,
             -827, -796, 372, 753, 519, 906
         ]), [
             -998, -882, -827, -817, -796, -731, -681, -657, -581, -523,
             -435, -387, -382, -331, -269, -255, -220, -216, -169, -163,
             -75, -43, -6, 80, 100, 180, 228, 280, 354, 366, 372, 382, 382,
             432, 471, 519, 652, 680, 747, 749, 753, 769, 771, 805, 847,
             906, 913, 956, 972, 980, 991
         ])
     self.assertEqual(
         insertionSort([
             384, -67, 120, 759, 697, 232, -7, -557, -772, -987, 687, 397,
             -763, -86, -491, 947, 921, 421, 825, -679, 946, -562, -626,
             -898, 204, 776, -343, 393, 51, -796, -425, 31, 165, 975, -720,
             878, -785, -367, -609, 662, -79, -112, -313, -94, 187, 260, 43,
             85, -746, 612, 67, -389, 508, 777, 624, 993, -581, 34, 444,
             -544, 243, -995, 432, -755, -978, 515, -68, -559, 489, 732,
             -19, -489, 737, 924
         ]), [
             -995, -987, -978, -898, -796, -785, -772, -763, -755, -746,
             -720, -679, -626, -609, -581, -562, -559, -557, -544, -491,
             -489, -425, -389, -367, -343, -313, -112, -94, -86, -79, -68,
             -67, -19, -7, 31, 34, 43, 51, 67, 85, 120, 165, 187, 204, 232,
             243, 260, 384, 393, 397, 421, 432, 444, 489, 508, 515, 612,
             624, 662, 687, 697, 732, 737, 759, 776, 777, 825, 878, 921,
             924, 946, 947, 975, 993
         ])
     self.assertEqual(
         insertionSort([
             544, -578, 556, 713, -655, -359, -810, -731, 194, -531, -685,
             689, -279, -738, 886, -54, -320, -500, 738, 445, -401, 993,
             -753, 329, -396, -924, -975, 376, 748, -356, 972, 459, 399,
             669, -488, 568, -702, 551, 763, -90, -249, -45, 452, -917, 394,
             195, -877, 153, 153, 788, 844, 867, 266, -739, 904, -154, -947,
             464, 343, -312, 150, -656, 528, 61, 94, -581
         ]), [
             -975, -947, -924, -917, -877, -810, -753, -739, -738, -731,
             -702, -685, -656, -655, -581, -578, -531, -500, -488, -401,
             -396, -359, -356, -320, -312, -279, -249, -154, -90, -54, -45,
             61, 94, 150, 153, 153, 194, 195, 266, 329, 343, 376, 394, 399,
             445, 452, 459, 464, 528, 544, 551, 556, 568, 669, 689, 713,
             738, 748, 763, 788, 844, 867, 886, 904, 972, 993
         ])
     self.assertEqual(
         insertionSort([
             -19, 759, 168, 306, 270, -602, 558, -821, -599, 328, 753, -50,
             -568, 268, -92, 381, -96, 730, 629, 678, -837, 351, 896, 63,
             -85, 437, -453, -991, 294, -384, -628, -529, 518, 613, -319,
             -519, -220, -67, 834, 619, 802, 207, 946, -904, 295, 718, -740,
             -557, -560, 80, 296, -90, 401, 407, 798, 254, 154, 387, 434,
             491, 228, 307, 268, 505, -415, -976, 676, -917, 937, -609, 593,
             -36, 881, 607, 121, -373, 915, -885, 879, 391, -158, 588, -641,
             -937, 986, 949, -321
         ]), [
             -991, -976, -937, -917, -904, -885, -837, -821, -740, -641,
             -628, -609, -602, -599, -568, -560, -557, -529, -519, -453,
             -415, -384, -373, -321, -319, -220, -158, -96, -92, -90, -85,
             -67, -50, -36, -19, 63, 80, 121, 154, 168, 207, 228, 254, 268,
             268, 270, 294, 295, 296, 306, 307, 328, 351, 381, 387, 391,
             401, 407, 434, 437, 491, 505, 518, 558, 588, 593, 607, 613,
             619, 629, 676, 678, 718, 730, 753, 759, 798, 802, 834, 879,
             881, 896, 915, 937, 946, 949, 986
         ])
     self.assertEqual(
         insertionSort([
             -823, 164, 48, -987, 323, 399, -293, 183, -908, -376, 14, 980,
             965, 842, 422, 829, 59, 724, -415, -733, 356, -855, -155, 52,
             328, -544, -371, -160, -942, -51, 700, -363, -353, -359, 238,
             892, -730, -575, 892, 490, 490, 995, 572, 888, -935, 919, -191,
             646, -120, 125, -817, 341, -575, 372, -874, 243, 610, -36,
             -685, -337, -13, 295, 800, -950, -949, -257, 631, -542, 201,
             -796, 157, 950, 540, -846, -265, 746, 355, -578, -441, -254,
             -941, -738, -469, -167, -420, -126, -410, 59
         ]), [
             -987, -950, -949, -942, -941, -935, -908, -874, -855, -846,
             -823, -817, -796, -738, -733, -730, -685, -578, -575, -575,
             -544, -542, -469, -441, -420, -415, -410, -376, -371, -363,
             -359, -353, -337, -293, -265, -257, -254, -191, -167, -160,
             -155, -126, -120, -51, -36, -13, 14, 48, 52, 59, 59, 125, 157,
             164, 183, 201, 238, 243, 295, 323, 328, 341, 355, 356, 372,
             399, 422, 490, 490, 540, 572, 610, 631, 646, 700, 724, 746,
             800, 829, 842, 888, 892, 892, 919, 950, 965, 980, 995
         ])
コード例 #21
0
import merge_sort

n=input("Enter a integer that represents the number of elements for the sort problem you want to simulate:")
n=int(n)
arr=[]
for i in range(n):
    arr.append(random.randint(0,n*10))
    
# printSome(arr,str="原始序列")
#深拷贝一份未排序数列
arr_bak=arr[:]
# printSome(arr_bak,str="复制的原始序列")

""" 开始比较计时:这一段可以考虑用函数式编程(函数作为参数) """
#统计插入排序的耗时
start_time1=time()
printSome(arr,str="插入排序之前:")
insertion_sort.insertionSort(arr)
end_time1=time()
printSome(arr,str="插入排序之后:")
print("the insertion sort takes time:%s" % (end_time1-start_time1))

#统计归并排序的耗时
start_time2=time()
printSome(arr_bak,str="归并排序之前:")
#注意,此归并排序的结果以MergeSort()函数返回来获得,并不会直接在参数列表中改动
arr_bak=merge_sort.MergeSort(arr_bak)
end_time2=time()
printSome(arr_bak,str="归并排序之后:")
print("the MergeSort sort takes time:%s" % (end_time2-start_time2))
コード例 #22
0
ファイル: tester.py プロジェクト: nhvantzelfde/sorting
def testSort(tests, n, minimum, maximum):
    time = [datetime.timedelta(0)] * 6
    for i in range(tests):
        ar = createArray(n, minimum, maximum)

        i_sort = list(ar)
        m_sort = list(ar)
        q_sort = list(ar)
        qr_sort = list(ar)
        h_sort = list(ar)

        d = datetime.datetime.now()
        insertion_sort.insertionSort(i_sort)
        time[0] += (datetime.datetime.now() - d)

        d = datetime.datetime.now()
        m_sort = merge_sort.mergeSort(m_sort)
        time[1] += (datetime.datetime.now() - d)

        d = datetime.datetime.now()
        quick_sort.quickSort(q_sort)
        time[2] += (datetime.datetime.now() - d)

        d = datetime.datetime.now()
        quick_sort.quickSortRand(qr_sort)
        time[3] += (datetime.datetime.now() - d)

        d = datetime.datetime.now()
        h_sort = heap_sort.heapSort(h_sort)
        time[4] += (datetime.datetime.now() - d)

        d = datetime.datetime.now()
        bible = sorted(ar)
        time[5] += (datetime.datetime.now() - d)

        error = False
        if not compareArrays(bible, i_sort):
            print "Insertion sort error: ar =", ar, ", i_sort =", i_sort, ", bible =", bible
            error = True
        if not compareArrays(bible, m_sort):
            print "Merge sort error: ar =", ar, ", m_sort =", m_sort, ", bible =", bible
            error = True
        if not compareArrays(bible, q_sort):
            print "Quick sort (deterministic) error: ar =", ar, ", q_sort =", q_sort, ", bible =", bible
            error = True
        if not compareArrays(bible, qr_sort):
            print "Quick sort (random) error: ar =", ar, ", qr_sort =", qr_sort, ", bible =", bible
            error = True
        if not compareArrays(bible, h_sort):
            print "Heap sort error: ar =", ar, ", h_sort =", h_sort, ", bible =", bible
            error = True

        if not error:
            print "Test", i + 1, "successful"

    print "Insertion sort time =", time[0]
    print "Merge sort time =", time[1]
    print "Quick sort (deterministic) time =", time[2]
    print "Quick sort (random) time =", time[3]
    print "Heap sort time =", time[4]
    print "Default Python sort time =", time[5]
コード例 #23
0
 def testInsertionSort_emptyArray_isNoop(self):
     A = []
     sort.insertionSort(A)
     self.assertEquals(A, list())
コード例 #24
0
def sorting_algorithms(arrayToBeSorted):
    # Calling Insertion sort and calculating time elapsed
    print("\n\n*********INSERTION SORT**********")
    #print("\nArray Before Sort")
    arrayToBeSorted1 = list(arrayToBeSorted)
    #print(arrayToBeSorted1)
    startTime1 = datetime.datetime.now()
    sorted_array = insertion_sort.insertionSort(arrayToBeSorted1)
    endTime1 = datetime.datetime.now()
    diff = endTime1 - startTime1
    timeElapsed1 = diff.total_seconds() * 1000
    #print ("\n\nSorted array after Insertion sort is:")
    #print(sorted_array)
    print("\nTime elapsed in milliseconds after Insertion sort is : ")
    print(timeElapsed1)

    # Calling merge sort and calculating time elapsed
    print("\n\n\n*********MERGE SORT**********")
    #print("\nArray Before Sort")
    arrayToBeSorted2 = list(arrayToBeSorted)
    #print(arrayToBeSorted2)
    n = len(arrayToBeSorted2)
    startTime2 = datetime.datetime.now()
    merge_sort.mergeSort(arrayToBeSorted2, 0, n - 1)
    endTime2 = datetime.datetime.now()
    diff = endTime2 - startTime2
    timeElapsed2 = diff.total_seconds() * 1000
    #print ("\n\nSorted array after merge sort is")
    #print (arrayToBeSorted2)
    print("\n\nTime elapsed in milliseconds after Merge-sort is : ")
    print(timeElapsed2)

    # Calling In-place quicksort sort and calculating time elapsed
    print("\n\n\n*********IN-PLACE QUICKSORT**********")
    #print("\nArray Before Sort")
    arrayToBeSorted3 = list(arrayToBeSorted)
    #print(arrayToBeSorted3)
    n = len(arrayToBeSorted3)
    startTime3 = datetime.datetime.now()
    inplace_quicksort.quickSort(arrayToBeSorted3, 0, n - 1)
    endTime3 = datetime.datetime.now()
    diff = endTime3 - startTime3
    timeElapsed3 = diff.total_seconds() * 1000
    #print ("\n\nSorted array after In-place quicksort is:")
    #print (arrayToBeSorted3)
    #for i in range(n):
    #print ("%d" %arrayToBeSorted3[i]),
    print("\n\nTime elapsed in milliseconds after Quicksort is : ")
    print(timeElapsed3)

    # Calling Modified Quicksort and calculating time elapsed
    print("\n\n\n*********MODIFIED QUICKSORT**********")
    #print("\nArray Before Sort")
    arrayToBeSorted4 = list(arrayToBeSorted)
    #print(arrayToBeSorted4)
    n = len(arrayToBeSorted4)
    startTime4 = datetime.datetime.now()
    modified_quicksort.quickSort(arrayToBeSorted4, 0, n - 1)
    endTime4 = datetime.datetime.now()
    diff = endTime4 - startTime4
    timeElapsed4 = diff.total_seconds() * 1000
    #print ("\n\nSorted array after Modified quicksort is:")
    #print (arrayToBeSorted4)
    print("\n\nTime elapsed in milliseconds after Modified Quicksort is : ")
    print(timeElapsed4)