Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fd94ca0

Browse files
Add files via upload
1 parent 49f7cc8 commit fd94ca0

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import random
2+
import time
3+
# sorting algorithms
4+
5+
def bubble_sort(arr):
6+
n = len(arr)
7+
for i in range(n):
8+
for j in range(0, n-i-1):
9+
if arr[j] > arr[j+1] :
10+
arr[j], arr[j+1] = arr[j+1], arr[j]
11+
12+
def insertion_sort(arr):
13+
count = 0
14+
for i in range(1, len(arr)):
15+
key = arr[i]
16+
j = i-1
17+
while j >= 0 and key < arr[j] :
18+
arr[j + 1] = arr[j]
19+
j -= 1
20+
arr[j + 1] = key
21+
22+
count+=1
23+
24+
def selection_sort(arr):
25+
for i in range(len(arr)):
26+
min_idx = i
27+
for j in range(i+1, len(arr)):
28+
if arr[min_idx] > arr[j]:
29+
min_idx = j
30+
arr[i],arr[min_idx] = arr[min_idx], arr[i]
31+
32+
def quick_sort(arr,low,high):
33+
34+
if len(arr) == 1:
35+
return arr
36+
if low < high:
37+
i = (low-1)
38+
pivot = arr[high]
39+
for j in range(low, high):
40+
if arr[j] <= pivot:
41+
i = i+1
42+
arr[i], arr[j] = arr[j], arr[i]
43+
arr[i+1], arr[high] = arr[high], arr[i+1]
44+
pi=(i+1)
45+
quick_sort(arr, low, pi-1)
46+
quick_sort(arr, pi+1, high)
47+
48+
49+
# serching algorithms
50+
def linear_search(arr):
51+
itemPos = 0
52+
itemFound = False
53+
while itemPos < len(array) and itemFound == False:
54+
if arr[itemPos] == itemWanted:
55+
itemFound = True
56+
else:
57+
itemPos +=1
58+
if itemFound == True:
59+
print("item at index ", itemPos)
60+
else:
61+
print("item not in list")
62+
63+
64+
def binary_search(arr, low, high):
65+
if high >= low:
66+
67+
mid = (high + low) // 2
68+
if arr[mid] == itemWanted:
69+
print("item at index ", mid)
70+
71+
elif arr[mid] > itemWanted:
72+
return binary_search(arr, low, mid-1)
73+
74+
else:
75+
return binary_search(arr, mid + 1, high)
76+
77+
else:
78+
print("item not in list")
79+
80+
81+
if __name__ == "__main__":
82+
array = []
83+
84+
itemWanted = 10
85+
length_of_list = 100000
86+
87+
# fills an array with random numbers from range specified
88+
for x in range(length_of_list):
89+
array.append(random.randint(0,length_of_list))
90+
start_time = time.time()
91+
# sorting algorithm
92+
93+
quick_sort(array,0,len(array)-1)
94+
95+
past_time=time.time() - start_time
96+
97+
print("--- %s seconds to sort ---" % (time.time() - start_time))
98+
# searching algorithm
99+
binary_search(array,0,len(array)-1)
100+
101+
print("--- %s seconds to find ---" % ((time.time() - start_time) - past_time))
102+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /