-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.py
More file actions
33 lines (27 loc) · 945 Bytes
/
BubbleSort.py
File metadata and controls
33 lines (27 loc) · 945 Bytes
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
nums = [9, 8, 7, 6, 5, 4, 3, 2, 1]
print("PRE SORT: {0}".format(nums))
def swap(arr, index_1, index_2):
temp = arr[index_1]
arr[index_1] = arr[index_2]
arr[index_2] = temp
def bubble_sort_unoptimized(arr):
iteration_count = 0
for el in arr:
for index in range(len(arr) - 1):
iteration_count += 1
if arr[index] > arr[index + 1]:
swap(arr, index, index + 1)
print("PRE-OPTIMIZED ITERATION COUNT: {0}".format(iteration_count))
def bubble_sort(arr):
iteration_count = 0
for i in range(len(arr)):
# iterate through unplaced elements
for idx in range(len(arr) - i - 1):
iteration_count += 1
if arr[idx] > arr[idx + 1]:
# replacement for swap function
arr[idx], arr[idx + 1] = arr[idx + 1], arr[idx]
print("POST-OPTIMIZED ITERATION COUNT: {0}".format(iteration_count))
bubble_sort_unoptimized(nums.copy())
bubble_sort(nums)
print("POST SORT: {0}".format(nums))