-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubble Sort
More file actions
49 lines (39 loc) · 1.34 KB
/
Bubble Sort
File metadata and controls
49 lines (39 loc) · 1.34 KB
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
# Sorting Algorithms - The Bubble Sort
"""
I just read up the main idea and concept behind one of the simplest sorting
algorithms out there; the Bubble Sort. It was easy enough to grasp and code
and I was able to get it running with no issues.
Basic Idea:
create two loops:
-an outer loop to iterate through n times
-an inner loop to iterate through the list of size len(original)-1
this is because of that's what the size would be when you pair up the neighbours
The inner loop swaps when its neighbour is smaller than it, and it does so by
assigning one value to a temporary value, overwriting that value, and then assinging the temporary
value to the other."""
test_arr = [2,3,1,1,5,4,5,7,8,1]
def BubbleSort(arr):
len_arr = len(arr)
for n in range(len_arr):
temp = -1
for i in range(len_arr - 1):
if arr[i] > arr[i+1]:
temp = arr[i]
arr[i] = arr[i+1]
arr[i+1] = temp
return arr
# OR
def BSort(arr):
N = len(arr)
swapped = False
for i in range(N):
temp = -1
swapped = False
for j in range(N-1):
if arr[j] > arr[j+1]:
temp, arr[j], arr[j+1] = arr[j], arr[j+1], arr[j]
swapped = True
if swapped == False:
break
return arr
print(BubbleSort(test_arr))