Created
March 7, 2018 20:43
-
-
Save joaofeitoza13/00465ecba595eacf16d478a1a0e16af5 to your computer and use it in GitHub Desktop.
Counting Sort implemented in python, ploted using matplotlib.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import matplotlib as mpl | |
mpl.use('Agg') | |
from random import randint | |
from timeit import timeit | |
import matplotlib.pyplot as plt | |
def reverseArray(lenght): | |
a = [] | |
for i in range(lenght): | |
a.append(lenght-i) | |
return a | |
def randomArray(length): | |
array = [] | |
tmp = 0 | |
while tmp < length: | |
num = randint(1, length*10) | |
if num not in array: | |
array.append(num) | |
tmp += 1 | |
return array | |
def countingSort(array): | |
countI = max(array) + 1 | |
countA = [0]*countI | |
position = 0 | |
for freq in array: | |
countA[freq] += 1 | |
for freq in range(countI): | |
for i in range(countA[freq]): | |
array[position] += 1 | |
position += 1 | |
return array | |
timeRandom = [] | |
timeReverse = [] | |
lengths = [] | |
elements = [1000, 3000, 6000, 9000, 12000, 15000, 18000, 21000, 24000] | |
def desenhaGrafico(xl = "Qnt. Elements(und)", yl = "Time(sec)"): | |
fig = plt.figure(figsize=(10, 8)) | |
plt.plot(lengths, timeRandom, label = "Random") | |
plt.plot(lengths, timeReverse, label = "Reverse") | |
plt.legend(bbox_to_anchor=(1, 1),bbox_transform=plt.gcf().transFigure) | |
plt.ylabel(yl) | |
plt.xlabel(xl) | |
plt.title('Gráfico Counting Sort',fontsize=20) | |
fig.savefig('grafico.png') | |
def main(): | |
for _tmp in elements: | |
lengths.append(_tmp) | |
arrayRandom = randomArray(_tmp) | |
arrayReverse = reverseArray(_tmp) | |
timeRandom.append(timeit("countingSort({})".format(arrayRandom), | |
setup = "from __main__ import countingSort", number = 1)) | |
timeReverse.append(timeit("countingSort({})".format(arrayReverse), | |
setup = "from __main__ import countingSort", number = 1)) | |
desenhaGrafico() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment