Sorting Algorithms - Py

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Sorting_algorithms.

py

1 import time
2 import random
3 def array(m):
4 arr=[]
5 for i in range(0,m):
6 a=random.randint(1,m*3)
7 arr.append(a)
8 return arr
9
10 def bubble_sort(a):
11 n = len(a)
12 for i in range(n):
13 for j in range(0, n-i-1):
14 if a[j] > a[j+1]:
15 a[j], a[j+1] = a[j+1], a[j]
16
17 def selection_sort(a):
18 n = len(a)
19 for i in range(n):
20 min_index = i
21 for j in range(i+1, n):
22 if a[j] < a[min_index]:
23 min_index = j
24 a[i], a[min_index] = a[min_index], a[i]
25
26 def insertion_sort(a):
27 n = len(a)
28 for i in range(n):
29 key = a[i]
30 j = i - 1
31 while j >= 0 and key < a[j]:
32 a[j+1] = a[j]
33 j -= 1
34 a[j+1] = key
35
36 def merge_sort(a):
37 n = len(a)
38 if n > 1:
39 mid = n // 2
40 left_half = a[:mid]
41 right_half = a[mid:]
42
43 merge_sort(left_half)
44 merge_sort(right_half)
45
46 i = k = j = 0
47
48 while i < len(left_half) and j < len(right_half):
49 if left_half[i] < right_half[j]:
50 a[k] = left_half[i]
51 i += 1
52 else:
53 a[k] = right_half[j]
54 j += 1
55 k += 1
56
57 while i < len(left_half):
58 a[k] = left_half[i]
59 i += 1
60 k += 1
61
62 while j < len(right_half):
63 a[k] = right_half[j]
64 j += 1
65 k += 1
66
67 def quick_sort(arr):
68 if len(arr) <= 1:
69 return arr
70
71 pivot = arr[len(arr) // 2]
72 left = [x for x in arr if x < pivot]
73 middle = [x for x in arr if x == pivot]
74 right = [x for x in arr if x > pivot]
75
76 return quick_sort(left) + middle + quick_sort(right)
77
78 def Time(t):
79 start = time.perf_counter()
80 bubble_sort(array(t))
81 end = time.perf_counter()
82 print("Bubblesort")
83 print("Time taken for",t,"value is", (end - start) * 10**6, "µs")
84
85 start = time.perf_counter()
86 selection_sort(array(t))
87 end = time.perf_counter()
88 print("Selectionsort")
89 print("Time taken for",t,"value is", (end - start) * 10**6, "µs")
90
91 start = time.perf_counter()
92 insertion_sort(array(t))
93 end = time.perf_counter()
94 print("Insertionsort")
95 print("Time taken for",t,"value is", (end - start) * 10**6, "µs")
96
97 start = time.perf_counter()
98 merge_sort(array(t))
99 end = time.perf_counter()
100 print("Mergesort")
101 print("Time taken for",t,"value is", (end - start) * 10**6, "µs")
102
103 start = time.perf_counter()
104 quick_sort(array(t))
105 end = time.perf_counter()
106 print("Quicksort")
107 print("Time taken for",t,"value is", (end - start) * 10**6, "µs")
108 print()
109 print()
110 print()
111
112 def main():
113 Time(5)
114 Time(10)
115 Time(100)
116 Time(1000)
117 Time(10000)
118 Time(100000)
119
120 if __name__ == "__main__":
121 main()
122
123

You might also like