-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSorting-Searching-Algorithm-Tester.py
104 lines (79 loc) · 2.59 KB
/
Sorting-Searching-Algorithm-Tester.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import random
import time
# sorting algorithms
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
def insertion_sort(arr):
count = 0
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >= 0 and key < arr[j] :
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
count+=1
def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[min_idx] > arr[j]:
min_idx = j
arr[i],arr[min_idx] = arr[min_idx], arr[i]
def quick_sort(arr,low,high):
if len(arr) == 1:
return arr
if low < high:
i = (low-1)
pivot = arr[high]
for j in range(low, high):
if arr[j] <= pivot:
i = i+1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
pi=(i+1)
quick_sort(arr, low, pi-1)
quick_sort(arr, pi+1, high)
# serching algorithms
def linear_search(arr):
itemPos = 0
itemFound = False
while itemPos < len(array) and itemFound == False:
if arr[itemPos] == itemWanted:
itemFound = True
else:
itemPos +=1
if itemFound == True:
print("item at index ", itemPos)
else:
print("item not in list")
def binary_search(arr, low, high):
if high >= low:
mid = (high + low) // 2
if arr[mid] == itemWanted:
print("item at index ", mid)
elif arr[mid] > itemWanted:
return binary_search(arr, low, mid-1)
else:
return binary_search(arr, mid + 1, high)
else:
print("item not in list")
if __name__ == "__main__":
array = []
itemWanted = 10854 # Item you want to search for
length_of_list = 10000000 # Amount of entries you want in your dataset
# Fills an array with random numbers from range specified
for x in range(length_of_list):
array.append(random.randint(0,length_of_list))
start_time = time.time()
# Add Sorting Algo of choice
quick_sort(array,0,len(array)-1)
past_time=time.time() - start_time
print("--- %s seconds to sort ---" % (time.time() - start_time))
# Add Searching Algo of choice
binary_search(array,0,len(array)-1)
print("--- %s seconds to find ---" % ((time.time() - start_time) - past_time))