Ejemplo n.º 1
0
def main():
    print("\nWelcome to the Student score locator\n")
    studentsList = [
        Student("Smith", "Joe", 78),
        Student("Lily", "Sanders", 89),
        Student("Maya", "Cooper", 94),
        Student("John", "Smith", 67),
        Student("Noble", "Barnes", 50),
        Student("Hewlett", "Packard", 88),
        Student("Harerra", "Jose", 95),
        Student("Sally", "Barnes", 77),
        Student("Mary", "Smith", 77),
        Student("John", "Doe", 83),
        Student("Raj", "Sharma", 56)
    ]

    insertionSort(studentsList)
    print("Students list in sorted order")
    for s in studentsList:
        print(s)

    print()
    ans = 'y'
    while (ans.lower() == 'y'):
        first = input("Please enter Student's first name: ")
        last = input("Please enter Student's last name: ")
        index = binarySearch2(Student(first, last, 0), studentsList)
        if (index >= 0):
            print("Score: ", studentsList[index].score)
        else:
            print("No student by that name")

        ans = input("Continue?(y/n) ")

    print("Goodbye")
Ejemplo n.º 2
0
def StartAlgorithm():
    global data
    if not data: return

    if algMenu.get() == 'Quick Sort':
        quick_sort(data, 0, len(data)-1, drawData, speedScale.get())
        drawData(data, ['green' for x in range(len(data))])
    
    elif algMenu.get() == 'Bubble Sort':
        bubble_sort(data, drawData, speedScale.get())
        
    elif algMenu.get() == 'Selection Sort':
        selectionSort(data, drawData, speedScale.get())
        
    elif algMenu.get() == 'Insertion Sort':
        insertionSort(data, drawData, speedScale.get())
        
        
    elif algMenu.get() == 'Merge Sort':
        merge_sort(data, drawData, speedScale.get())
        
    drawData(data, ['green' for x in range(len(data))])
Ejemplo n.º 3
0
def test_insertionSort():
    mylist = [12, 34, 67, 45, 23, 36, 5, 17, 40, 10]
    sorted_list = insertionSort(mylist)
    assert sorted_list == [5, 10, 12, 17, 23, 34, 36, 40, 45, 67]
Ejemplo n.º 4
0
    print("4   -   Merge sort\n")
    print("5   -   Heap sort\n")
    print("6   -   Counting sort\n")
    print("7   -   Radix sort\n")
    print("0   -   Quit\n")
    userSelection = input()

    #Run the selected algorithm
    if userSelection == '1':
        startTime = time.time()
        selectionsort.selectionSort(alist)
        endTime = time.time()
        resultsFile.write("You chose Selection sort\n")
    elif userSelection == '2':
        startTime = time.time()
        insertionsort.insertionSort(alist)
        endTime = time.time()
        resultsFile.write("You chose Insertion sort\n")
    elif userSelection == '3':
        startTime = time.time()
        alist = quicksort.quickSort(alist)
        endTime = time.time()
        resultsFile.write("You chose Quick sort\n")
    elif userSelection == '4':
        startTime = time.time()
        mergesort.mergeSort(alist)
        endTime = time.time()
        resultsFile.write("You chose Merge sort\n")
    elif userSelection == '5':
        startTime = time.time()
        heapsort.heapSort(alist)
# -*- coding: utf-8 -*-
## Insertion sort timer
# P12.5

from random import randint
from insertionsort import insertionSort
from time import time

# Prompt the user for the list size.
n = int(input("Enter list size: "))

# Construct random list.
values = []
for i in range(n):
    values.append(randint(1, 100))   

startTime = time()
insertionSort(values)
endTime = time()
      
print("Elapsed time: %.3f seconds" % (endTime - startTime))
Ejemplo n.º 6
0
 def test_1(self):
     arr = [1, 3, 4, 5, 2, 0]
     res = insertionsort.insertionSort(arr)
     self.assertEqual(res, [0, 1, 2, 3, 4, 5])
def main():
    # List to sort
    num_bars = DATA_SIZE[0] // (BAR_WIDTH + 1)
    arr = [DATA_SIZE[1] // num_bars * i for i in range(1, num_bars)]

    # Window layout
    graph = sg.Graph(GRAPH_SIZE, (0, 0), DATA_SIZE, background_color='#F5F6F4')
    layout = [[
        sg.Text('Visualization',
                size=(30, 1),
                font=("Helvetica", 25),
                background_color='#8F90A0',
                text_color='#FFFFFF')
    ], [graph],
              [
                  sg.Button('Select sorting method',
                            button_color=['#FFFFFF', '#35343B'],
                            font=("Helvetica", 12)),
                  sg.Button('Generate new array',
                            button_color=['#FFFFFF', '#35343B'],
                            font=("Helvetica", 12))
              ]]

    window = sg.Window('Algorithm Visualizer', layout)
    window.Finalize()

    draw_bars(graph, arr)

    while True:
        event, values = window.read()
        if event in (None, 'Exit'):
            break

        if event == 'Generate new array':
            graph.Erase()
            random.shuffle(arr)
            draw_bars(graph, arr)

        if event == 'Select sorting method':
            l2 = [[
                sg.T('Choose sorting method',
                     font=("Helvetica", 12),
                     background_color='#8F90A0',
                     text_color='#FFFFFF')
            ], [
                sg.Listbox(['Bubble', 'Insertion', 'Selection'], size=(16, 3))
            ], [sg.Ok()]]
            w2 = sg.Window('Choose sorting method', l2)
            button, values = w2()
            w2.close()
            try:
                if values[0][0] == 'Bubble':
                    sort = bubblesort.bubbleSort(arr)
                    sortmethod = 'Bubble'

                elif values[0][0] == 'Insertion':
                    sort = insertionsort.insertionSort(arr)
                    sortmethod = 'Insertion'

                else:
                    sort = selectionsort.selectionSort(arr)
                    sortmethod = 'Selection'
            except:
                sg.Popup('None selected.',
                         font=("Helvetica", 12),
                         background_color='#8F90A0',
                         text_color='#FFFFFF')
                continue

            timeout = 10

            for partially_sorted_list in sort:
                event, values = window.read(timeout=timeout)
                if event is None:
                    break
                graph.Erase()
                draw_bars(graph, partially_sorted_list)
                timeout = int(10)
            sg.Popup(f'{sortmethod} sort done.',
                     font=("Helvetica", 12),
                     background_color='#8F90A0',
                     text_color='#FFFFFF')
import random as rnd
import time

from insertionsort import insertionSort
from quicksort import quickSort

num_elements = 20000  # lunghezza della lista da ordinare

unaLista = []
# generiamo una lista di 10000 interi a caso
for i in range(num_elements):
    unaLista.append(rnd.randint(1, 100000))

start = time.time()  # segna il tempo di inizio nella variabile start
insertionSort(unaLista)
stop = time.time()  # segna il tempo di fine nella variabile start
print('Insertion sort per', stop - start, "secondi.")

unaLista = []
for i in range(num_elements):
    unaLista.append(rnd.randint(1, 100000))

start = time.time()  # segna il tempo di inizio nella variabile start
quickSort(unaLista)
stop = time.time()  # segna il tempo di fine nella variabile start
print('Quick Sort per', stop - start, "secondi.")

unaLista = []
for i in range(num_elements):
    unaLista.append(rnd.randint(1, 100000))
Ejemplo n.º 9
0
def executeAlgos():
	# yield 'Starting executeAlgos...\n'

	shortSize = 10
	popSize = shortSize * 10
	shortData = random.sample(range(0, popSize), shortSize) # Generate Random data
	copyShortData = copy.deepcopy(shortData) # Maintain a copy for other algorithms
	print ("Generated random short data with %d elements\n"%shortSize)
	print "short data = "+ str(shortData) + "\n"
	stdout.flush()
	# yield ("Generated random short data with %d elements"%shortSize)

	# ------- SMALL DATASETS SORTING --------
	# Merge sort : small dataset
	startTime = datetime.datetime.now()
	mergeSort(shortData)
	endTime = datetime.datetime.now()
	elapsedTime = endTime - startTime
	print "Merge sorted short data = "+ str(shortData) + " in "+str(elapsedTime)+"\n"
	stdout.flush()
	# yield "\nMerge sorted short data = "+ str(shortData) + " in "+str(elapsedTime)

	# Quick sort : small dataset
	shortData = copy.deepcopy(copyShortData)
	startTime = datetime.datetime.now()
	quickSort(shortData)
	endTime = datetime.datetime.now()
	elapsedTime = endTime - startTime
	print "Quick sorted short data = "+ str(shortData) + " in "+str(elapsedTime) + "\n"
	stdout.flush()
	# yield "\nQuick sorted short data = "+ str(shortData) + " in "+str(elapsedTime)
		
	# Heap sort : small dataset
	shortData = copy.deepcopy(copyShortData)
	startTime = datetime.datetime.now()
	heapSort(shortData)
	endTime = datetime.datetime.now()
	elapsedTime = endTime - startTime
	print "Heap sorted short data = "+ str(shortData) + " in "+str(elapsedTime) + "\n"
	stdout.flush()
	# yield "\nQuick sorted short data = "+ str(shortData) + " in "+str(elapsedTime)

	# Insertion sort : small dataset
	shortData = copy.deepcopy(copyShortData)
	startTime = datetime.datetime.now()
	insertionSort(shortData)
	endTime = datetime.datetime.now()
	elapsedTime = endTime - startTime
	print "Insertion sorted short data = "+ str(shortData) + " in "+str(elapsedTime)+ "\n"
	stdout.flush()
	
	# Selection sort : small dataset
	shortData = copy.deepcopy(copyShortData)
	startTime = datetime.datetime.now()
	selectionSort(shortData)
	endTime = datetime.datetime.now()
	elapsedTime = endTime - startTime
	print "Selection sorted short data = "+ str(shortData) + " in "+str(elapsedTime)+ "\n"
	stdout.flush()
	



	# -------- LARGE DATA -------

	print '\n\n--------- Large data sets ---------\n\n' 	

	largeSize = 10000    # Data set size for large data set demonstration
	popSize = largeSize * 10 # Domain of random numbers allowed in random data set
	largeData = random.sample(range(0, popSize), largeSize) # Genrate Random data
	copyLargeData = copy.deepcopy(largeData) # Maintain a copy for other algorithms
	print ("Generated random large data with %d elements\n"%largeSize)
	# print "Large data = "+ str(largeData)+"\n"
	stdout.flush()
	# yield ("Generated random large data with %d elements"%largeSize)

	# Merge sort : large dataset
	print 'Merge sorting large data (%d elements)...\n' %( largeSize) 
	stdout.flush()
	startTime = datetime.datetime.now()
	mergeSortLargeData = copy.deepcopy(copyLargeData) # Maintain a copy for other algorithms
	mergeSort(mergeSortLargeData)
	endTime = datetime.datetime.now()
	elapsedTime = endTime - startTime
	print ("Merge sorted large data (%d elements) in "%( largeSize) + str(elapsedTime) ) + "\n"
	stdout.flush()
	# yield ("Merge sorted large data (%d elements) in "%( largeSize) + str(elapsedTime) )

	# Quick sort : large dataset
	print 'Quick sorting large data (%d elements)...\n' %( largeSize) 
	stdout.flush()
	quickSortLargeData = copy.deepcopy(copyLargeData)
	startTime = datetime.datetime.now()
	quickSort(quickSortLargeData)
	endTime = datetime.datetime.now()
	elapsedTime = endTime - startTime
	print ("Quick sorted large data (%d elements) in "%( largeSize) + str(elapsedTime)+ "\n" )
	stdout.flush()
	# yield ("Quick sorted large data (%d elements) in "%( largeSize) + str(elapsedTime) )

	# Heap sort : large dataset
	print 'Heap sorting large data (%d elements)...\n' %( largeSize) 
	stdout.flush()
	heapSortLargeData = copy.deepcopy(copyLargeData)
	startTime = datetime.datetime.now()
	heapSort(heapSortLargeData)
	endTime = datetime.datetime.now()
	elapsedTime = endTime - startTime
	print ("Heap sorted large data (%d elements) in "%( largeSize) + str(elapsedTime)+ "\n" )
	stdout.flush()
	# yield ("Quick sorted large data (%d elements) in "%( largeSize) + str(elapsedTime) )


	# Insertion sort : large dataset
	print 'Insertion sorting large data (%d elements)...\n' %( largeSize) 
	stdout.flush()
	insertionSortLargeData = copy.deepcopy(copyLargeData)
	startTime = datetime.datetime.now()
	insertionSort(insertionSortLargeData)
	endTime = datetime.datetime.now()
	elapsedTime = endTime - startTime
	print ("Insertion sorted large data (%d elements) in "%( largeSize) + str(elapsedTime)+ "\n" )
	stdout.flush()
	
	# Selection sort : large dataset
	print 'Selection sorting large data (%d elements)...\n' %( largeSize) 
	stdout.flush()
	largeSelectionSortData = copy.deepcopy(copyLargeData)
	startTime = datetime.datetime.now()
	selectionSort(largeSelectionSortData)
	endTime = datetime.datetime.now()
	elapsedTime = endTime - startTime
	print ("Selection sorted large data (%d elements) in "%( largeSize) + str(elapsedTime) + "\n")
	stdout.flush()
	

	print "Printing large data sets...\n"
	print "Raw large data set = "+ str(largeData)+"\n\n\n\n"
	print "\n\n ------ Sorted Large Data sets ------\n\n"
	print "Merge sorted large data = "+ str(mergeSortLargeData)+"\n\n\n\n"
	print "Quick Sorted large data = "+ str(quickSortLargeData)+"\n\n\n\n"
	print "Heap Sorted large data = "+ str(heapSortLargeData)+"\n\n\n\n"
	print "Insertion Sorted large data = "+ str(insertionSortLargeData)+"\n\n\n\n"
	print "Selection Sorted large data = "+ str(selectionSortLargeData)+"\n\n\n\n"
	print '\nAlgorithms execution ended ...\n'
	stdout.flush()
Ejemplo n.º 10
0
n = int(input("Enter list size: "))

# Construct random lists.
values = []
for i in range(n):
    values.append(randint(1, 100))
values2 = list(values)
values3 = list(values)

startTime = time()
shellSort(values)
endTime = time()

print("Elapsed time with Shell sort: %.3f seconds" % (endTime - startTime))

startTime = time()
quickSort(values2, 0, n - 1)
endTime = time()

print("Elapsed time with quicksort: %.3f seconds" % (endTime - startTime))

for i in range(n):
    if values[i] != values2[i]:
        raise RuntimeError("Incorrect sort result.")

startTime = time()
insertionSort(values3)
endTime = time()

print("Elapsed time with insertion sort: %.3f seconds" % (endTime - startTime))