Advertisement
Szczepan86

Algorytmy

Oct 13th, 2018
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1. # sortowanie zwariowane (Bogo Sort)
  2.  
  3. from random import *
  4. from time import *
  5.  
  6. # utworz 'ziarno' do tworzenia losowej listy
  7. seed()
  8.  
  9. # utworz pusta liste elementow
  10. x = []
  11.  
  12. # utworz losowa liste elementow o wielkosci N
  13. for i in range(0, 1000):
  14.     x.append(randint(0, 10000))
  15.  
  16. # funkcja sprawdzająca, czy dane są posortowane
  17. def posortowane(x):
  18.     i = 0
  19.     j = len(x)
  20.     while i + 1 < j:
  21.         if x[i] > x[i + 1]:
  22.             return False
  23.         i += 1
  24.     return True
  25.  
  26. def bogo(x):
  27.     # tak dlugo, jak dane nie sa posortowane, dokonuj przetasowania wartosci
  28.     while not posortowane(x):
  29.         shuffle(x)
  30.     return x
  31.  
  32. def stupidsort(x):
  33.     n = len(x)-1 # indeks ostatniego elementu
  34.     while True:
  35.         i = 0
  36.         while True:
  37.             if x[i] > x[i+1]:
  38.                 temp = x[i+1]
  39.                 x[i+1] = x[i]
  40.                 x[i] = temp
  41.                 break
  42.             i = i + 1
  43.            
  44.             if i == n:
  45.                 return x # lista jest posortowana
  46.  
  47. def bubblesort(x):
  48.     n = len(x)-1 # indeks ostatniego elementu
  49.     for j in range(0, n):
  50.         for i in range(0, n):
  51.             if x[i] > x[i+1]:
  52.                 x[i], x[i+1] = x[i+1], x[i]
  53.     return x
  54.      
  55. def selectionsort(x):
  56.     n = len(x)-1 # indeks ostatniego elementu
  57.     for j in range(0, n):
  58.         pmin = j
  59.         for i in range(j+1, n):
  60.             if x[i] < x[pmin]:
  61.                 pmin = i
  62.         x[pmin], x[j] = x[j], x[pmin]
  63.     return x
  64.    
  65. start = time()
  66. print("Wylosowana lista: ")
  67. print(x)
  68. x = selectionsort(x)
  69. print("Lista posortowana: ")
  70. print(x)
  71. czas = time() - start
  72. print(str(czas) + " seconds")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement