Skip to content

Instantly share code, notes, and snippets.

@joaofeitoza13
Created March 2, 2018 19:52
Show Gist options
  • Save joaofeitoza13/b48332d3c6e6201c6211d6d2a8eeabd0 to your computer and use it in GitHub Desktop.
Save joaofeitoza13/b48332d3c6e6201c6211d6d2a8eeabd0 to your computer and use it in GitHub Desktop.
Shellsort implemented in python, ploted using matplotlib
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 shellsort(array):
gap = len(array) // 2
while gap > 0:
for i in range(gap):
for j in range(i+gap, len(array), gap):
_tmp = array[j]
pos = j
while pos>=gap and array[pos] > array[pos-gap]:
array[pos] = array[pos-gap]
pos = pos-gap
array[pos] = _tmp
gap = gap // 2
return array
timeRandom = []
timeReverse = []
lengths = []
elements = [1000, 3000, 6000, 9000, 12000, 15000, 18000, 21000, 24000]
def desenhaGrafico(xl = "Qnt. Elements(und)", yl = "Time(sec)"):
plt.title('Shellsort Analysis', fontsize=20)
plt.plot(lengths, timeRandom, label = "Random")
plt.plot(lengths, timeReverse, label = "Reverse - Worse")
legend = plt.legend(loc='upper left', shadow=True)
frame = legend.get_frame()
frame.set_facecolor('0.90')
plt.xlabel(xl)
plt.ylabel(yl)
plt.show()
def main():
for _tmp in elements:
lengths.append(_tmp)
arrayRandom = randomArray(_tmp)
arrayReverse = reverseArray(_tmp)
timeRandom.append(timeit("shellsort({})".format(arrayRandom),
setup = "from __main__ import shellsort", number = 1))
timeReverse.append(timeit("shellsort({})".format(arrayReverse),
setup = "from __main__ import shellsort", 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