コード例 #1
0
def main():
    setup()
    screen = s.screen
    isStart = False
    done = False
    while not done:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    s.array.clear()
                    s.numColor.clear()
                    setup()
                if event.key == pygame.K_q:
                    isStart = True
                    sortType = 0
                if event.key == pygame.K_b:
                    isStart = True
                    sortType = 1

        screen.fill(s.Colors[0])

        if not isStart:
            s.drawScreen()
        else:
            if sortType == 0:
                quick.quickSort(s.array, 0, len(s.array) - 1)
            if sortType == 1:
                bubble.bubbleSort(s.array)

        pygame.display.flip()

    pygame.quit()
コード例 #2
0
ファイル: main.py プロジェクト: binaryitch/Sort
def main():
	toSort = list(range(0, 21))
	fyShuffle(toSort)
	bubbleSort(toSort)
	fyShuffle(toSort)
	insertionSort(toSort)
	fyShuffle(toSort)
	mergeSort(toSort)
	fyShuffle(toSort)
	quickSort(toSort)
	fyShuffle(toSort)
	selectionSort(toSort)

	toSearch = [-16, -8, -4, -2, -1, 0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096]
	for i in range (0, len(toSearch)):
		binarySearch(toSearch, toSearch[i] - 1)
		binarySearch(toSearch, toSearch[i])
		binarySearch(toSearch, toSearch[i] + 1)
	
	for i in range (0, len(toSearch)):
		interpolationSearch(toSearch, toSearch[i] - 1)
		interpolationSearch(toSearch, toSearch[i])
		interpolationSearch(toSearch, toSearch[i] + 1)

	toSearch = [-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10]
	for i in range (0, len(toSearch)):
		binarySearch(toSearch, toSearch[i] - 1)
		binarySearch(toSearch, toSearch[i])
	
	for i in range (0, len(toSearch)):
		interpolationSearch(toSearch, toSearch[i] - 1)
		interpolationSearch(toSearch, toSearch[i])
コード例 #3
0
def startAlgorithm():
    global data
    disableWidgets()
    if algMenu.get()=='Bubble Sort':
        bubbleSort(data, drawData, speedScale.get())
    elif algMenu.get() == 'Merge Sort':
        merge_sort(data, drawData, speedScale.get())
    elif algMenu.get() == 'Quick Sort':
        quick_sort(data, 0, len(data)-1, drawData, speedScale.get())
        drawData(data, ['green' for x in range(len(data))])
コード例 #4
0
def startAlgorithm():
    global data
    #check which algorithm is selected
    if algoMenu.get() == 'Bubble Sort':
        bubbleSort(data, draw, speed.get())
    elif algoMenu.get() == 'Merge Sort':
        mergeSort(data, draw, speed.get())
    elif algoMenu.get() == 'Selection Sort':
        selectionSort(data, draw, speed.get())
    elif algoMenu.get() == 'Insertion Sort':
        insertionSort(data, draw, speed.get())
    elif algoMenu.get() == 'Quick Sort':
        quick_sort(data, 0, len(data) - 1, draw, speed.get())
        draw(data, ['green' for x in range(len(data))])
コード例 #5
0
ファイル: test.py プロジェクト: Sarveshgithub/Python-DS-ALgo
def checkInputs(n, array):
    if n == len(array) and len(array) > 1:
        array = [int(array[i]) for i in range(len(array))]
        removeDups = list(set(array))
        sortArray = bubbleSort(removeDups)
        return sortArray[len(sortArray) - 2]
    else:
        return "please enter correct values"
コード例 #6
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))])
コード例 #7
0
ファイル: app.py プロジェクト: annaelvira24/Sorting-Tutorial
def get_sort():
    restemp = []
    if (request.json and request.json['array']
            and isinstance(request.json['array'], list)
            and len(request.json['array']) > 0
            and len(request.json['array']) <= 10
            and isinstance(request.json['array'][0], int)
            and request.json['method']
            and request.json['method'] in ['bubble', 'merge']
            and isinstance(request.json['asc'], bool)):
        if (request.json['method'] == 'bubble'):
            bubbleSort.bubbleSort(restemp, request.json['array'],
                                  request.json['asc'])
        else:
            mergeSort.mergeSort(restemp, request.json['array'],
                                request.json['asc'])
        return jsonify({'res': restemp})

    else:
        return jsonify(
            {'res': 'Input is not valid, please input 1 up to 10 numbers'})
コード例 #8
0
def sorting():
    """Выбор сортировки из выпадающего списка"""
    global array
    sorting_speed = 0.2  #задаем скорость демонстрации в диапазоне от 0.1 до 1
    if (selected_algorithm.get() == "Сортировка пузырьком"):
        bubbleSort(array, demoArray, sorting_speed)
        demoArray(array, ['#77E596' for element in range(len(array))])
    elif (selected_algorithm.get() == "Сортировка вставками"):
        insertSort(array, demoArray, sorting_speed)
        demoArray(array, ['#77E596' for element in range(len(array))])
    elif (selected_algorithm.get() == "Сортировка выбором"):
        selectSort(array, demoArray, sorting_speed)
        demoArray(array, ['#77E596' for element in range(len(array))])
    elif (selected_algorithm.get() == "Сортировка слиянием"):
        mergeSort(array, 0, len(array) - 1, demoArray, sorting_speed)
        demoArray(array, ['#77E596' for element in range(len(array))])
    elif (selected_algorithm.get() == "Быстрая сортировка"):
        quickSort(array, 0, len(array) - 1, demoArray, sorting_speed)
        demoArray(array, ['#77E596' for element in range(len(array))])
    elif (selected_algorithm.get() == "Сортировка Шелла"):
        shellSort(array, demoArray, sorting_speed)
        demoArray(array, ['#77E596' for element in range(len(array))])
コード例 #9
0
ファイル: test.py プロジェクト: gdssouza/sorting-algorithms
def main():
    # array original
    array = [5, 4, 6, 2, 1, 7, 0, 3, 8, 9]
    # resultados
    array_select = selectSort(array)
    array_bubble = bubbleSort(array)
    # gabarito
    gabarito = array.copy()
    gabarito.sort()

    # saidas
    print("Array Original: ", array)
    print("Array Select:   ", array_select)
    print("Array Bubble:   ", array_bubble)
    print("Array Gabarito: ", gabarito)
コード例 #10
0
def timeElapsed(algoritmo, arr):
	start_time = time.time()
	comparaciones = 0
	
	if(algoritmo == "merge"):
		comparaciones = mergeSort.mergeSort(arr)
	elif(algoritmo == "quickStatic"):
		comparaciones = quickSortStaticPiv.quickSort(arr)
	elif(algoritmo == "quickAle"):
		comparaciones = quickSortRandomPiv.quickSort(arr)
	elif(algoritmo == "heap"):
		comparaciones = heapSort.heapSort(arr)
	elif(algoritmo == "bubble"):
		comparaciones = bubbleSort.bubbleSort(arr)

	elapsed_time = time.time() - start_time
	print("TamList: ", len(arr), "\tTime: ", elapsed_time, "Comps: ", comparaciones)
コード例 #11
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()
コード例 #12
0
 def test_unsorted_array(self):
     input = [1, 5, 63, 3, 54, 1]
     self.assertEqual(bubbleSort(input), sorted(input),
                      "Should be [1, 1, 3, 5, 54, 63]")
コード例 #13
0
 def test_empty_array(self):
     input = []
     self.assertEqual(bubbleSort(input), sorted(input), "Should be []")
コード例 #14
0
    lista = []
    for i in range(tam):
        lista.append(i)
    random.shuffle(lista)
    return lista


def geraListaReversa(tam):
    lista = []
    for i in range(tam):
        lista.append(i)
    lista.reverse()
    return lista


'''
vet = bubbleSort([7, 6, 5, 4, 3, 2, 1])
print(vet.vet)
#print(vet.stats.swaps)
vet.sort()
print(vet.vet)
#print(vet.stats.swaps)
'''
intervals = [100, 200, 300, 400, 500]
vectMelhor = bubbleSort(geraListaOrdenada(500), intervals)
vectPior = bubbleSort(geraListaReversa(500), intervals)
vect = bubbleSort(geraLista(500), intervals)
E1 = Experiment([vect, vectMelhor, vectPior], intervals, title="Bubble Sort")
E1.calculaTempos(bubbleSort)
E1.plotar()
x = 1
コード例 #15
0
    for j in range(0, n):
        arr.append(random.randrange(0, 1000, 1))
    start_time = time.time()
    array = quickSort.quicksort(arr, 0, len(arr) - 1)
    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])
コード例 #16
0
 def test_emptyList(self):
     emptyList = []
     expectedList = []
     self.assertEqual(bubbleSort.bubbleSort(emptyList), expectedList)
コード例 #17
0
 def test_case1(self):
     test1 = [5, 2, 1, 3, 4]
     output = bubbleSort(test1)
     self.assertEqual(output, [1, 2, 3, 4, 5])
コード例 #18
0
 def testBubbleSort(self):
     A = [5, 1, 3, 0, 10]
     bubbleSort.bubbleSort(A)
     B = [0, 1, 3, 5, 10]
     if (A != B):
         self.fail("bubbleSort method fails.")
コード例 #19
0
    x1, y1 = [], []
    x2, y2 = [], []
    x3, y3 = [], []
    x4, y4 = [], []
    for scale in range(10, 5000+step, step):
        print(scale, end = "\r")
        s = np.random.randint(0,50,(scale))
        
        start = time.time()
        _ = quickSort(s)
        end = time.time()
        x1.append(scale)
        y1.append(end-start)
        
        start = time.time()
        _ = bubbleSort(s)
        end = time.time()
        x2.append(scale)
        y2.append(end-start)
        
        start = time.time()
        _ = insertSort(s)
        end = time.time()
        x3.append(scale)
        y3.append(end-start)

        start = time.time()
        _ = selectSort(s)
        end = time.time()
        x4.append(scale)
        y4.append(end-start)
コード例 #20
0
import bubbleSort as st

testList = [5, 4, 3, 6, 10, 1, 2, 3]

print(st.bubbleSort(testList))
コード例 #21
0
 def test_basicSort(self):
     unsortedList = [3, 2, 1]
     expectedList = [1, 2, 3]
     self.assertEqual(bubbleSort.bubbleSort(unsortedList), expectedList)
コード例 #22
0
 def test_negative(self):
     unsortedList = [-1, -2, -3]
     expectedList = [-3, -2, -1]
     self.assertEqual(bubbleSort.bubbleSort(unsortedList), expectedList)
コード例 #23
0
 def test_sortCharacters(self):
     unsortedList = ['b', 'a', 'c']
     expectedList = ['a', 'b', 'c']
     self.assertEqual(bubbleSort.bubbleSort(unsortedList), expectedList)
コード例 #24
0
 def test_backwards_array(self):
     input = [5, 4, 3, 2, 1]
     self.assertEqual(bubbleSort(input), sorted(input),
                      "Should be [1, 2, 3, 4, 5]")
コード例 #25
0
def main():
    window.fill((255, 255, 255))
    query = [random.randrange(20, 400) for i in range(100)]

    c = [135, 206, 235]
    start = 100
    i = start
    j = 0
    while i < 1000 + start:
        pygame.draw.line(window, c, (i, 500), (i, 500 - query[j]), 5)
        j += 1
        i += 10
        pygame.display.update()

    s = 80
    quick = button(mnt, 10 + s, 520, 180, 50, "quickSort")
    button.draw(quick, window)

    merge = button(mnt, 210 + s, 520, 180, 50, "mergeSort")
    button.draw(merge, window)

    selection = button(mnt, 400 + s, 520, 200, 50, "selectionSort")
    button.draw(selection, window)

    insertion = button(mnt, 610 + s, 520, 200, 50, "insertionSort")
    button.draw(insertion, window)

    bubble = button(mnt, 820 + s, 520, 200, 50, "bubbleSort")
    button.draw(bubble, window)

    speed = Slider("Speed", 0.025, 0.05, 0, 630)

    pygame.display.update()

    pause = button(mnt, 450, 520, 160, 50, "start/stop")

    run = True

    while run:
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                pos = pygame.mouse.get_pos()
                if quick.isOver(pos):
                    clearinstruction(window, pause)
                    #message("illustrating ..quickSort",window)
                    quickSort(query, 0, 99, window, pause, speed, 0.025)
                    run = False
                elif merge.isOver(pos):
                    clearinstruction(window, pause)
                    #message("illustrating ..mergeSort",window)
                    mergeSort(query, 0, 99, window, pause, speed)
                    run = False
                elif selection.isOver(pos):
                    clearinstruction(
                        window,
                        pause)  #message("illustrating ..selectionSort",window)
                    selectionSort(query, 0, 99, window, pause, speed)
                    run = False
                elif insertion.isOver(pos):
                    clearinstruction(
                        window,
                        pause)  #message("illustrating ..insertionSort",window)
                    insertionSort(query, 0, 99, window, pause, speed)
                    run = False
                elif bubble.isOver(pos):
                    #message("illustrating ..bubbleSort",window)
                    clearinstruction(window, pause)
                    bubbleSort(query, window, pause, speed)
                    run = False
            elif event.type == pygame.QUIT:
                pygame.quit()

    clearInstruction(window)
    restart = button(mnt, 550, 520, 120, 50, "restart")
    button.draw(restart, window)
    pygame.display.update()

    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                break
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and restart.isOver(
                    pygame.mouse.get_pos()):
                try:
                    main()
                except:
                    pass

    pygame.quit()
コード例 #26
0
 def test_already_sorted(self):
     input = [0, 1, 2, 3, 4, 5]
     self.assertEqual(bubbleSort(input), sorted(input),
                      "Should be [0,1,2,3,4,5]")
コード例 #27
0
ファイル: parseHTML.py プロジェクト: geopopos/SortClasses
        if (courseDays[i][j] == "M"):
            monday.append(i)
        elif (courseDays[i][j] == "W"):
            wednesday.append(i)
        elif (courseDays[i][j] == "F"):
            friday.append(i)
        elif (courseDays[i][j] == "T"):
            if (j + 1 > len(courseDays[i])):
                tuesday.append(i)
            elif (j + 1 < len(courseDays[i]) and courseDays[i][j + 1] == "T"):
                tuesday.append(i)
            elif (j + 1 < len(courseDays[i]) and courseDays[i][j + 1] == "H"):
                thursday.append(i)
print len(monday)
dayLabel = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
day = [monday, tuesday, wednesday, thursday, friday]

#Sort Classes By Time
bubbleSort.bubbleSort(day, courseTimesValue)

#Print Classes
for i in range(0, len(day)):
    print(dayLabel[i])
    print("_________________________")
    for j in range(0, len(day[i])):
        index = day[i][j]
        print(courseDepartment[index] + " " + str(courseNumber[index]) + " " +
              str(courseSection[index]) + " " + courseDays[index] + "     " +
              courseTimes[index])
    print("\n")
コード例 #28
0
ファイル: sortTester.py プロジェクト: aridokmecian/PySort
from bubbleSort import bubbleSort

arr = [4, 3, 22, 3, 431, 1]
print(arr)
print(bubbleSort(arr))
print(arr)
コード例 #29
0
import bubbleSort


class binarySearch(object):
    def __init__(self, x, d):
        self.x = x
        self.d = d

    def binarySearch(self):
        lower = 0
        upper = len(self.x) - 1
        while lower <= upper:
            mid = (lower + upper) // 2
            if self.x[mid] < self.d:
                lower = mid + 1
            elif self.x[mid] > self.d:
                upper = mid - 1
            else:
                return mid
        return -1


if __name__ == '__main__':
    x = [3, 20, 9, 15, 2]
    bubbleSortAg = bubbleSort.bubbleSort(x)
    xSort = bubbleSortAg.bubbleSort()
    d = 15
    binarySearchAg = binarySearch(xSort, d)
    print(xSort)
    print(binarySearchAg.binarySearch())
コード例 #30
0
import bubbleSort
import selectionSort
import insertSort
import shellSort
import mergeSort

list = [2, 5, 60, 43, 27, 10, 89, 17]
print('\nData yang akan di sort :\n', list)
print('\nBubble Sort :\n')
bubbleSort.bubbleSort(list)
print("\n==================================================\n")

print('\nSelection Sort :\n')
selectionSort.selectionSort(list)
print("\n==================================================\n")

print('\nInsert Sort :\n')
insertSort.insertionSort(list)
print("\n==================================================\n")

sublist = len(list)
shellSort.shellSort(list)
print("\nShell Sort :\n")
for i in range(sublist):
    print(list[i])
print("\n==================================================\n")

print('\nMerge Sort :\n')
mergeSort.mergeSort(list)
print("\n==================================================\n")
コード例 #31
0
 def test_alreadySorted(self):
     sortedList = [1, 2, 3]
     expectedList = [1, 2, 3]
     self.assertEqual(bubbleSort.bubbleSort(sortedList), expectedList)