Пример #1
0
def timeAlgorithm(array, algorithm):
    if algorithm == "counting":
        start = time.time_ns()
        countingSort(array)
        end = time.time_ns()
    elif algorithm == "quick":
        start = time.time_ns()
        quickSort(array, 0, len(array) - 1)
        end = time.time_ns()
    elif algorithm == "insertion":
        start = time.time_ns()
        insertionSort(array)
        end = time.time_ns()
    elif algorithm == "merge":
        start = time.time_ns()
        mergeSort(array)
        end = time.time_ns()
    elif algorithm == "heap":
        start = time.time_ns()
        heapSort(array, 0, len(array))
        end = time.time_ns()
    elif algorithm == "intro":
        start = time.time_ns()
        introSort(array)
        end = time.time_ns()

    else:
        return 1
    return end - start
Пример #2
0
def introSortRec(array, start, end, maxDepth):
    if end - start > 1:
        array, pivot = partition(array, start, end)
        if maxDepth == 0:
            heapSort(array, start, end)
        elif start < end:
            introSortRec(array, start, pivot, maxDepth - 1)
            introSortRec(array, pivot + 1, end, maxDepth - 1)
Пример #3
0
def generateAndTime(arraySize):
    array = np.random.rand(arraySize)
    t1 = time.time()
    heapSort(array)
    t2 = time.time()
    # print(array)
    elapsed = t2 - t1
    return elapsed
Пример #4
0
def sampleMedianSelect(list, left, right, m):
    if m >= len(list[left:right + 1]):
        #print("m>len(list)->decreasing m")
        m = len(list[left:right + 1])
    S = random.sample(list[left:right + 1], m)
    if m <= 20:
        selectionSort(S)
    else:
        heapSort(S)
    return S[ceil(len(S) / 2)]
Пример #5
0
def sort_all(N): # num of array = 2**N
    input = read_input(N)  #读取待排序数据,input为python list
    ret = {}     #python 字典
    ret["origin"] = input   #初始数据
    
    #ret["merge_sort"][0] 存放排序结果 ret["merge_sort"][1] 存放排序所花时间,下同
    begin = time.time()
    ret["merge_sort"] = [ mergeSort(input.copy(), 0, len(input) - 1)  ]
    end = time.time()
    ret["merge_sort"].append(end - begin)

    begin = time.time()
    ret["heap_sort"]  = [   heapSort(input.copy())  ]
    end = time.time()
    ret["heap_sort"].append(end - begin)

    begin = time.time()
    ret["quick_sort"] = [   quickSort(input.copy(), 0, len(input) - 1)  ]
    end = time.time()
    ret["quick_sort"].append(end - begin)

    begin = time.time()
    ret["count_sort"] = [   countSort(input.copy(), 65536)  ]
    end = time.time()
    ret["count_sort"].append(end - begin)

    return ret
Пример #6
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()

    heapSort(myList)

    endSort = time.perf_counter()

    #print( "Sorted List:  ", myList)
    print("Total heap sort time of", n,
          "random items %7.6f" % (endSort - start))
Пример #7
0
def startAlgorithm():
    global data
    if not data: return

    if(algMenu.get() == 'Bubble Sort'):
        bubbleSort(data, drawData, speedScale.get())
    elif(algMenu.get() == 'Quick Sort'):
        quickSort(data, drawData, speedScale.get())
        drawData(data, ['green' for x in range(len(data))])
    elif(algMenu.get() == 'Insertion Sort'):
        insertionSort(data, drawData, speedScale.get())
    elif(algMenu.get() == 'Selection Sort'):
        selectionSort(data, drawData, speedScale.get())
    elif (algMenu.get() == 'Heap Sort'):
        heapSort(data, drawData, speedScale.get())
    elif (algMenu.get() == 'Merge Sort'):
        mergeSort(data, drawData, speedScale.get())
        drawData(data, ['green' for x in range(len(data))])
Пример #8
0
def introSort(array, begin=0, end=None, depth=0, *, reverse=False):
    if end is None:
        end = len(array) - 1

    if depth < log2(len(array)):
        if begin < end:
            mid = partition(array, begin, end, reverse=reverse)
            introSort(array, begin, mid - 1, depth + 1, reverse=reverse)
            introSort(array, mid + 1, end, depth + 1, reverse=reverse)
    else:
        array[begin:end + 1] = heapSort(array[begin:end + 1], reverse=reverse)
Пример #9
0
def main(filename, e):
    try:
        fd = open(filename, 'r')
    except:
        print('Unable to open file')
        exit(-1)
    _items = fd.read()
    items = map(lambda x: int(x), _items.split())
    items = heapSort.heapSort(items)
    print('Sorted list = %s' %items)
    index = findIndex(items, e)
    print(index)
Пример #10
0
def timeElapsed(algoritmo, arr):
	start_time = time.time()
	comparaciones = 0
	
	if(algoritmo == "quickStatic"):
		comparaciones = quickSortStaticPiv.quickSort(arr)
	elif(algoritmo == "quickAle"):
		comparaciones = quickSortRandomPiv.quickSort(arr)
	elif(algoritmo == "heap"):
		comparaciones = heapSort.heapSort(arr)
	
	elapsed_time = time.time() - start_time
	print("TamList: ", len(arr), "\tTime: ", elapsed_time, "Comps: ", comparaciones)
Пример #11
0
def quicheSortRec(lst, limit):
    """
    A non in-place, depth limited quickSort, using median-of-3 pivot.
    Once the limit drops to 0, it uses heapSort instead.
    """
    if lst == []:
        return lst
    
    if limit==0:
        return heapSort.heapSort(lst)
    else:
        pivot= qsPivotMedian3.medianOf3(lst)        #  select the first element as the pivot
        less, same, more = qsPivotFirst.partition(pivot, lst)
        return quicheSortRec(less,limit-1) + same + quicheSortRec(more,limit-1)           
Пример #12
0
def sampleMedianSelect(list, left, right, m):
    if m >= len(list[left:right + 1]):
        print(
            "m>len(list)->decreasing m"
        )  # il caso in cui m sia più grande dell'array viene gestito portandolo
        m = len(
            list[left:right + 1]
        )  # alla minima grandezza accettabile affinche l'algoritmo funzioni
        # cosi in un caso pratico in cui verrebbe utilizzato in qualche applicazione
    S = random.sample(
        list[left:right + 1], m
    )  # in cui m è scelto a caso l'algoritmo non si ferma,al massimo rallenta un po'
    if m <= 20:  # oppure potrebbe anche non accadere mai con opportuni controlli a monte
        bubbleSort(
            S
        )  # nella scelta di m da parte dell'utente o dalla funzione chiamante
        #inserctionSort(S)
        #selectionSort(S)
    else:
        #S.sort()
        #mergeSort(S)
        #quickSort(S)
        heapSort(S)
    return S[ceil(len(S) / 2)]
Пример #13
0
def quicheSortRec(lst, limit):
    """
    A non in-place, depth limited quickSort, using median-of-3 pivot.
    Once the limit drops to 0, it uses heapSort instead.
    """
    if lst == []:
        return lst

    if limit == 0:
        return heapSort.heapSort(lst)
    else:
        pivot = qsPivotMedian3.medianOf3(
            lst)  #  select the first element as the pivot
        less, same, more = qsPivotFirst.partition(pivot, lst)
        return quicheSortRec(less, limit - 1) + same + quicheSortRec(
            more, limit - 1)
Пример #14
0
def sortAlgo():
    global boo
    global array
    global barRec
    global epochs

    epochs = [0]
    boo = True

    try:
        size = int(sizeEntry.get())
    except:
        size = 15
    if size < 0:
        size = 1

    #change the value of the speed selected
    s = 1001 - speed.get()

    #decide the algo
    if algDropDown.get() == "Merge Sort":
        algo = mergeSort(array, 0, size - 1)
    elif algDropDown.get() == "Bubble Sort":
        algo = bubbleSort(array)
    elif algDropDown.get() == "Quick Sort":
        algo = quickSort(array, 0, size - 1)
    elif algDropDown.get() == "Insertion Sort":
        algo = insertionSort(array)
    elif algDropDown.get() == "Selection Sort":
        algo = selectionSort(array)
    elif algDropDown.get() == "Heap Sort":
        algo = heapSort(array)
    elif algDropDown.get() == "Radix Sort":
        algo = radixSort(array)

    #start animation
    anima = anim.FuncAnimation(fig,
                               func=updatePlot,
                               fargs=(barRec, epochs),
                               frames=algo,
                               interval=s,
                               repeat=False,
                               blit=False)
    anima._start()
Пример #15
0
def quipSortRec(lst, limit):
    """
    A non in-place, depth limited quickSort, using median-of-3 pivot.
    Once the limit drops to 0, it uses heapSort instead.
    """
    if len(lst) == 1 or lst == []:
        return lst
    if limit <= 0:
        return heapSort.heapSort(lst)
    pivot = [median([lst[0], lst[len(lst) // 2], lst[len(lst) - 1]])]
    lst2 = []
    lst3 = []
    for i in lst:
        if i < pivot[0]:
            lst2.append(i)
        elif i > pivot[0]:
            lst3.append(i)
        else:
            pivot.append(i)
    return quipSortRec(lst2, limit - 1) + pivot + quipSortRec(lst3, limit - 1)
Пример #16
0
def quipSortRec(lst, limit):
    """
    A non in-place, depth limited quickSort, using median-of-3 pivot.
    Once the limit drops to 0, it uses heapSort instead.
    """
    if len(lst) == 1 or lst == []:
        return lst
    if limit <= 0:
        return heapSort.heapSort(lst)
    pivot = [median([lst[0], lst[len(lst) // 2], lst[len(lst) - 1]])]
    lst2 = []
    lst3 = []
    for i in lst:
        if i < pivot[0]:
            lst2.append(i)
        elif i > pivot[0]:
            lst3.append(i)
        else:
            pivot.append(i)
    return quipSortRec(lst2, limit - 1) + pivot + quipSortRec(lst3, limit - 1)
Пример #17
0
def sort_me_timed_heap(arr):
    heapSort.heapSort(heapSort.makeHeap(arr))
Пример #18
0
    def test_heapSort(self):
        arr1 = [2, 5, 3, 10, 12]
	    sortedArray = heapSort(arr1)
	    result = np.arrayEqual([2, 3, 5, 10, 12], sortedArray)
	    self.assertTrue(result)
Пример #19
0
        end = time.time()
        print(end - start)
    print "END"
print "----------------------------------"

for j in range(0, number_of_element):
    for i in range(0, number_of_array):
        #now = datetime.datetime.now()           #print the time and date for the record
        #print now
        start = time.time()
        #sorted(array[i])
        #mergeSort(array_set1[j][i])
        #quickSortHoare(array_set[j][i])
        #quickSortLomuto(array[i])
        #quickSortOpenSource(array[i])
        heapSort(array_set2[j][i])
        #array[i] = quickSort(array[i])
        end = time.time()
        print(end - start)
    print "END"
print "----------------------------------"

for j in range(0, number_of_element):
    for i in range(0, number_of_array):
        #now = datetime.datetime.now()           #print the time and date for the record
        #print now
        start = time.time()
        #sorted(array[i])
        #mergeSort(array_set1[j][i])
        #quickSortHoare(array_set[j][i])
        #quickSortLomuto(array[i])
Пример #20
0
            end = time()
            temp = end - start
            print("Sample sorted with bubbleSort time -->", temp)

            # OTHER SORTING ALGHORITMS

            A = B
            start = time()
            mergeSort(A)  # mergeSort
            end = time()
            temp = end - start
            print("Array sorted with mergeSort time-->", temp)

            A = B
            start = time()
            heapSort(A)  # heapSort
            end = time()
            temp = end - start
            print("Array sorted with heapSort time-->", temp)

            A = B
            start = time()
            quickSort(A, False)  # non-deterministic quickSort
            end = time()
            temp = end - start
            print(
                "Array sorted with classic non-deterministic quickSort time-->",
                temp)

            A = B
            start = time()
Пример #21
0
 def test_SortByHeap(self):
     nums=[3,1,2,5,6,7,8,10,2,4]
     heapSort(nums,len(nums)-1)
     self.assertEqual([1,2,2,3,4,5,6,7,8,10],nums);
Пример #22
0
 def testHeapSort(self):
     A = [5, 1, 3, 0, 10]
     heapSort.heapSort(A)
     B = [0, 1, 3, 5, 10]
     if (A != B):
         self.fail("heapSort method fails.")
Пример #23
0
def comp(list1, list2):
    for val in list1:
        if val in list2:
            return True
    return False


"""
for i in range (0,len_each_array):
    print i,
    testArray[i].sort()
    print len(testArray[i]),
    quickSortHoare(testArrayCopy[i])
    print len(testArrayCopy[i])
"""

len_array_test = len(arrayTest)

for i in range(0, len_array_test):
    for j in range(0, 5):
        print i, j, len(arrayTest[i][j]),
        arrayTest[i][j].sort()
        #arrayTestCopy[i][j] = quickSort(arrayTestCopy[i][j])
        #quickSortOpenSource(arrayTestCopy[i][j])
        #mergeSort(arrayTestCopy[i][j])
        heapSort(arrayTestCopy[i][j])
        if comp(arrayTestCopy[i][j], arrayTestCopy[i][j]) == True:
            print "PASS"
        else:
            print "FAIL"
Пример #24
0
    print("The quick sorted array with size ", len(array), "is ")
    for i in range(0, len(array)):
        print("array[", i, "] = ", array[i])
    end_time = time.time()
    quick_sort_time = end_time - start_time
    print("Quick sort time for size", n, "is ", quick_sort_time)

    arr.clear()
    for j in range(0, n):
        arr.append(random.randrange(0, 1000, 1))
    start_time = time.time()
    array = bubbleSort.bubbleSort(arr)
    print("The bubble sorted array with size ", len(array), "is ")
    for i in range(0, len(array)):
        print("array[", i, "] = ", array[i])
    end_time = time.time()
    bubble_sort_time = end_time - start_time
    print("Bubble sort time for size", n, "is ", bubble_sort_time)

    arr.clear()
    for j in range(0, n):
        arr.append(random.randrange(0, 1000, 1))
    start_time = time.time()
    array = heapSort.heapSort(arr)
    print("The Heap sorted array with size ", len(array), "is ")
    for i in range(0, len(array)):
        print("array[", i, "] = ", array[i])
    end_time = time.time()
    heap_sort_time = end_time - start_time
    print("Heap sort time for size", n, "is ", heap_sort_time)
Пример #25
0
import TestHelper
import MergeSort
import QuickSort
import heapSort
from time import time

l = TestHelper.CreateRandomIntList(100000, 10, 9000000)
lc = list(l)
t0 = time()

qck = QuickSort.QuickSort(l)
t1 = time()
s = MergeSort.MergeSort(l)
t2 = time()
heapSort.heapSort(lc)
t3 = time()
print((l[99], s[99]))
print((l[99], qck[99]))
print((l[99], lc[99]))

print('function vers1 takes %f' % (t1 - t0))
print('function vers2 takes %f' % (t2 - t1))
print('function vers3 takes %f' % (t3 - t2))