Exemple #1
0
def test_quicksort(cases: int = 20):
    import test
    import sorts
    for i in range(cases):
        lst = test.random_array()
        # print('lst: ',lst)
        lstcopy = lst[:]
        sorts.quicksort(lstcopy, 0, len(lstcopy))
        print('sorted lst: ', lstcopy)
        test.equal_list(lstcopy, sorted(lst))

    print('{ message: no other things means everything is ok! }')

    lst = [2, 1, 2, 2, 2, 2, 2, 2, 2]
    sorts.quicksort(lst, 0, len(lst))
    print('lst: ', lst)
Exemple #2
0
    def sort(self, var, loops):
        sort_algo = var.get()

        lst = [x + 1 for x in range(loops)]
        random.seed(time.time())
        random.shuffle(lst)

        if sort_algo == "Insertion":
            A = sorts.insertionsort(lst)
        elif sort_algo == "Bubble":
            A = sorts.bubblesort(lst)
        elif sort_algo == "Merge":
            A = sorts.mergesort(lst, 0, loops - 1)
        elif sort_algo == "Quick":
            A = sorts.quicksort(lst, 0, loops - 1)
        elif sort_algo == "Selection":
            A = sorts.selectionsort(lst)

        title = sort_algo + " Sort"
        fig, ax = plt.subplots()
        ax.set_title(title)
        bar_rects = ax.bar(range(len(lst)), lst, align="edge")
        ax.set_xlim(0, len(lst))
        ax.set_ylim(0, int(1.07 * max(lst)))
        text = ax.text(0.02, 0.95, "", transform=ax.transAxes)
        iteration = [0]

        def update_fig(lst, rects, iteration):
            for rect, val in zip(rects, lst):
                rect.set_height(val)
            iteration[0] += 1
            text.set_text("# of operations: {}".format(iteration[0]))

        canvas = FigureCanvasTkAgg(fig, master=self)
        canvas.get_tk_widget().place(x=30, y=80)

        anim = animation.FuncAnimation(fig, func=update_fig,
                                       fargs=(bar_rects, iteration), frames=A, interval=1,
                                       repeat=False, blit=False)
        # return anim
        plt.show()


        """def reset():
Exemple #3
0
    return len(book_a['author_lower']) + len(book_a['title_lower']) > len(
        book_b['author_lower']) + len(book_b['title_lower'])


# Comparison functions end

bookshelf = utils.load_books('books_small.csv')
bookshelf_v1 = bookshelf.copy()
bookshelf_v2 = bookshelf.copy()

long_bookshelf = utils.load_books('books_large.csv')

sort_1 = sorts.bubble_sort(bookshelf, by_title_ascending)
sort_2 = sorts.bubble_sort(bookshelf, by_author_ascending)
# sort_3 = sorts.bubble_sort(long_bookshelf, by_total_length)
'''
for book in sort_1:
  print(book['title'])

for book in sort_2:
  print(book['author'])

sorts.quicksort(bookshelf_v2, 0, len(bookshelf_v2) - 1, by_author_ascending)
for book in bookshelf_v2:
  print(book['author'])

'''

sorts.quicksort(long_bookshelf, 0, len(long_bookshelf) - 1, by_total_length)
for book in long_bookshelf:
    print(len(book['author_lower']) + len(book['title_lower']))
Exemple #4
0
def by_title_ascending(book_a, book_b):
    return book_a['title_lower'] > book_b['title_lower']


def by_author_ascending(book_a, book_b):
    return book_a['author_lower'] > book_b['author_lower']


def by_total_length(book_a, book_b):
    return len(book_a['author_lower']) + len(book_a['title_lower']) > len(
        book_b['author_lower']) + len(book_b['title_lower'])


sort_1 = bubble_sort(bookshelf, by_title_ascending)
for book in sort_1:
    print(book['title'])

sort_2 = bubble_sort(bookshelf_v1, by_author_ascending)
for book in sort_2:
    print(book['author'])

quicksort(bookshelf_v2, 0, len(bookshelf_v2) - 1, by_author_ascending)
book_2 = [book['author_lower'] for book in bookshelf_v2]
print(book_2)

# sort_3 = bubble_sort(long_bookshelf, by_total_length)

quicksort(long_bookshelf, 0, len(long_bookshelf) - 1, by_total_length)
book_3 = [book['author_lower'] for book in long_bookshelf]
print(book_3)
#sort_1 = sorts.bubble_sort(bookshelf, by_title_ascending)
# for book in sort_1:
# print(book['title'])

print(
    "\n-----------Start of Bubble Sort /w by_author_ascending on bookshelf_v1\n"
)
sort_2 = sorts.bubble_sort(bookshelf_v1, by_author_ascending)
# for book in sort_2:
# print(book['author'])

print(
    "\n-----------Start of Quick Sort /w by_author_ascending on bookshelf_v2\n"
)
sorts.quicksort(bookshelf_v2, 0, len(bookshelf_v2) - 1, by_author_ascending)
print("Quik sort: There were {0} swaps".format(sorts.quick_swaps))
# for book in bookshelf_v2:
# print(book['author'])

#### Sorts on long_bookshelf
print(
    "\n-----------Start of Bubble Sort /w by_total_length on long_bookshelf\n")
sorts.bubble_sort(long_bookshelf, by_total_length)

print(
    "\n-----------Start of Quick Sort /w by_total_length on long_bookshelf_v1\n"
)
sorts.quicksort(long_bookshelf_v1, 0,
                len(long_bookshelf_v1) - 1, by_total_length)
print("Quik sort: There were {0} swaps".format(sorts.quick_swaps))
Exemple #6
0
def test(nStart, nmax, gap):

    pmedia = 1

    row = ['n', 'mergeTime', 'quickTime', 'heatTime']
    with open('testInsert.csv', 'w') as csvFile:
        writer = csv.writer(csvFile)
        writer.writerow(row)
    csvFile.close()

    for n in range(nStart, nmax, gap):

        mergeTimes = np.arange(pmedia, dtype='f')
        heapTimes = np.arange(pmedia, dtype='f')
        quickTimes = np.arange(pmedia, dtype='f')

        for y in range(pmedia):
            B = np.arange(n)
            np.random.shuffle(B)
            A = sorts.heapArray(B)
            C = B.copy()

            startMerge = timer()
            sorts.mergesort(B, 0, n - 1)  # passare lunghezza - 1
            endMerge = timer()
            mergeTimes[y] = endMerge - startMerge

            startQuick = timer()
            sorts.quicksort(C, 0, n - 1)
            endQuick = timer()
            quickTimes[y] = endQuick - startQuick

            startHeap = timer()
            sorts.heapsort(A)
            endHeap = timer()
            heapTimes[y] = endHeap - startHeap

        mergeTime = np.mean(mergeTimes)
        quickTime = np.mean(quickTimes)
        heapTime = np.mean(heapTimes)

        dataCsv = [n, mergeTime, quickTime, heapTime]
        with open('testInsert.csv', 'a') as csvFile:
            writer = csv.writer(csvFile)
            writer.writerow(dataCsv)
        csvFile.close()

    data = np.loadtxt('testInsert.csv',
                      delimiter=",",
                      skiprows=1,
                      usecols=[0, 1, 2, 3])

    f = plt.figure(1)
    f.set_figheight(10)
    f.set_figwidth(10)
    plt.subplot(111)
    plt.plot(data[:, 0], data[:, 1], label='mergeTime')
    plt.plot(data[:, 0], data[:, 2], label='quickTime')
    plt.plot(data[:, 0], data[:, 3], label='heapTime')
    plt.xlabel('n')
    plt.ylabel('time(s)')
    plt.title("sort algorithms")
    plt.legend()

    plt.show()
    while inicio <= fim:
        midrange = (inicio + fim) // 2
        if x == vetor[midrange]:
            return print(midrange)
        if x < vetor[midrange]:
            fim = midrange - 1
        else:
            inicio = midrange + 1

    return -1  #não enncontrado


#x = int(input("Valor que deseja encontrar no vetor"))
vetor = random.sample(range(20000), 20000)  #cria um vetor
vetor2 = vetor.copy()
#vetor_arrumado = bubble_sort(vetor) #chama o bubble sort

#tam = len(vetor_arrumado)
tama = len(vetor)
#print(vetor)
#bubble_sort(vetor2)
#print(vetor)
t1 = time.time()
quicksort(vetor, 0, tama - 1)
t2 = time.time()
print('O algoritmo quicksort levou {} para organizar o vetor'.format(t2 - t1))
#binary_search2(vetor_arrumado, x, tam) #chama a função de busca binaria iterativa

#binary_search(vetor_arrumado, 0, len(vetor_arrumado)-1, x)
for book in sort_1:
  print(book['title'])
  
def by_author_ascending(book_a, book_b):
  return book_a['author_lower'] > book_b['author_lower']  

bookshelf_v1 = bookshelf.copy()
sort_2 = sorts.bubble_sort(bookshelf_v1, by_author_ascending)
for book in sort_2:
  print(book['author'])

#14.Within script.py create another copy of bookshelf as bookshelf_v2.  
bookshelf_v2 = bookshelf.copy()

#15.Perform quicksort on bookshelf_v2 using by_author_ascending. This implementation operates on the input directly, so does not return a list.
#Print the authors in bookshelf_v2 to ensure they are now sorted correctly.
sorts.quicksort(bookshelf_v2, 0, len(bookshelf_v2) - 1, by_author_ascending)
for book in bookshelf_v2:
  print(book['author'])

def by_total_length(book_a, book_b):
  return len(book_a['author_lower']) + len(book_a['title_lower']) > len(book_b['author_lower']) + len(book_b['title_lower'])

long_bookshelf = utils.load_books('books_large.csv')
sort_3 = sorts.bubble_sort(long_bookshelf, by_total_length)
for book in sort_3:
  print(book['author'])



Exemple #9
0
print()


def by_author_ascending(book_a, book_b):
    return book_a['author_lower'] > book_b['author_lower']


bookshelf_v1 = bookshelf[:]
# or bookshelf_v1 = bookshelf.copy()

sort2 = sorts.bubble_sort(bookshelf, by_author_ascending)
for i in bookshelf:
    print(f'Title: {i["title"]}\nAuthor: {i["author"]}')

bookshelf_v2 = bookshelf[:]
sorts.quicksort(bookshelf_v2, by_author_ascending)
print()
for i in bookshelf:
    print(f'Title: {i["title"]}\nAuthor: {i["author"]}')


def by_total_length(book_a, book_b):
    return (len(book_a['author']) + len(book_a['title'])) > (
        len(book_b['author']) + len(book_b['title']))


long_bookshelf = utils.load_books('books_large.csv')
print()
sort3 = sorts.bubble_sort(bookshelf, by_total_length)

for i in bookshelf:
    if len_a > len_b:
        return True
    else:
        return False


#testing algorithmen
ordered_v1_bookshelf = sorts.bubble_sort(bookshelf, by_title_ascending)
# for book in ordered_v1_bookshelf:
# print(book["title"])

ordered_v2_bookshelf = sorts.bubble_sort(bookshelf, by_author_ascending)
# for book in ordered_v2_bookshelf:
# print(book["author"])

ordered_v3_bookshelf = bookshelf[:]
sorts.quicksort(ordered_v3_bookshelf, 0,
                len(ordered_v3_bookshelf) - 1, by_author_ascending)
# for book in ordered_v3_bookshelf:
# print(book["author"])

ordered_v4_bookshelf = sorts.bubble_sort(long_bookshelf, by_total_length)
# for book in ordered_v4_bookshelf:
# print(book["author"] + " " + book["title"])

ordered_v5_bookshelf = long_bookshelf[:]
sorts.quicksort(ordered_v5_bookshelf, 0,
                len(ordered_v5_bookshelf) - 1, by_total_length)
for book in ordered_v5_bookshelf:
    print(book["author"] + " " + book["title"])
Exemple #11
0
# hint #2: "Could a bit vector be useful?" (#111)

# well ... the bits of each char a string would also map to unique bitstrings
# the entire string itself would map to a unique bitstring

# I don't see any performance improvement above O(n) though...

# ------------------------------
# hint #3:  "Could you solve it in O(n log n) time?"
#           "What might a solution look like?"      (#132)

# O(n log n) implies we are sorting the data using with QuickSort
# (or a similar time-complexity sort algo)

# A linear pass to check duplicates would add an additional O(n) algo

# We have sort: some f1 that's O(N log N) and linear pass: f2 that's O(N),
# Then sort + linear pass is O(max(f1, f2))
# = O(max(n, n log n))
# = O(n log n).

# Implement sorts in sorts.py
from sorts import quicksort

print(s1)
s1 = list(s1)
s2 = list(s2)

quicksort(s1, 0, len(s1) - 1)
quicksort(s2, 0, len(s2) - 1)
Exemple #12
0
def by_author_ascending(book_a, book_b):
    return book_a['author_lower'] > book_b['author_lower']


def by_total_length(book_a, book_b):
    return len(book_a['author_lower']) + len(book_a['title_lower']) > len(
        book_b['author_lower']) + len(book_b['title_lower'])

sort_long = sorts.bubble_sort(long_bookshelf_v2, by_title_ascending)


''',
           number=5000)
print(b)
print('Quicksort')
c = timeit('''
import utils
import sorts
from timeit import timeit

bookshelf = utils.load_books('books_small.csv')
bookshelf_v1 = bookshelf.copy()
bookshelf_v2 = bookshelf.copy()
long_bookshelf = utils.load_books('books_largs.csv')
long_bookshelf_v1 = long_bookshelf.copy()

for book in bookshelf:
    book['author_lower'] = book['author'].lower()
    book['title_lower'] = book['title'].lower()

for book in long_bookshelf:
Exemple #13
0
def by_title_ascending(book_a, book_b):
    return book_a['title_lower'] > book_b['title_lower']


def by_author_ascending(book_a, book_b):
    return book_a["author_lower"] > book_b["author_lower"]


def by_total_length(book_a, book_b):
    return len(book_a["title_lower"]) + len(book_a["author_lower"]) > len(
        book_b["title_lower"]) + len(book_b["author_lower"])


sort_1 = bubble_sort(bookshelf, by_title_ascending)
sort_2 = bubble_sort(bookshelf_copy_v1, by_author_ascending)
quicksort(bookshelf_copy_v2, 0,
          len(bookshelf_copy_v2) - 1, by_author_ascending)
sort_4 = bubble_sort(bookshelf, by_total_length)
quicksort(bookshelf_copy_v3, 0, len(bookshelf_copy_v3) - 1, by_total_length)

print("\nBubble Sort - by_title_ascending")
for book in sort_1:
    print(book['title_lower'])

print("\nBubble Sort - by_author_ascending")
for book in sort_2:
    print(book['author_lower'])

print("\nQuick Sort - by_author_ascending")
for book in bookshelf_copy_v2:
    print(book['author_lower'])
Exemple #14
0
        return True
    else:
        False


def by_total_length(book_a, book_b):
    return len(book_a['title_lower']) + len(book_a['author_lower']) > len(
        book_b['author_lower']) + len(book_b['title_lower'])


bookshelf = utils.load_books('books_small.csv')
long_bookshelf = utils.load_books('books_large.csv')
bookshelf_v1 = bookshelf.copy()
bookshelf_v2 = bookshelf.copy()

sort_1 = sorts.bubble_sort(bookshelf, by_title_ascending)
sort_2 = sorts.bubble_sort(bookshelf_v1, by_author_ascending)
sorts.quicksort(bookshelf_v2, 0, len(bookshelf_v2) - 1, by_total_length)
sorts.quicksort(long_bookshelf, 0, len(long_bookshelf) - 1, by_title_ascending)

# for book in sort_1:
#   print(book['title'])
# for book in sort_2:
#   print(book['title'])

for book in long_bookshelf:
    print(book['title'])

# print(ord("a"))
# print(ord(" "))
# print(ord("A"))
    print(book['title'])


# Author comparison function:
def by_author_ascending(book_a, book_b):
    return book_a['author_lower'] > book_b['author_lower']


bubble_sorted_by_author = sorts.bubble_sort(bookshelf_copy_one,
                                            by_author_ascending)

print()
for book in bubble_sorted_by_author:
    print(f"{book['title']} by {book['author']}")

sorts.quicksort(bookshelf_copy_two, 0,
                len(bookshelf_copy_two) - 1, by_author_ascending)

print()
for book in bookshelf_copy_two:
    print(f"{book['title']} by {book['author']}")


# Length comparison function:
def by_total_length(book_a, book_b):
    return len(book_a["title"]) + len(book_a["author"]) > len(
        book_b["title"]) + len(book_b["author"])


long_bookshelf = utils.load_books(book_large__csv_path)

# bubble_sorted_by_length= sorts.bubble_sort(long_bookshelf, by_total_length)