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 e64848f

Browse files
Bubble Sort
1 parent 51867c9 commit e64848f

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

‎README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,6 @@ Data Structures and Algorithms Patterns implemented in Python.
2222
- [x] [Searching Alogorithms](Searching-Algo)
2323
- [x] [Linear Search](Searching-Algo/linearsearch.py)
2424
- [x] [Binary Search](Searching-Algo/binarysearch.py)
25+
- [x] [Sorting Alogorithms](Sorting-Algo)
26+
- [x] [Bubble Sort](Sorting-Algo/bubblesort.py)
2527

‎Sorting-Algo/bubblesort.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
'''
2+
Bubble Sort
3+
Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them until they are not in the intended order.
4+
'''
5+
6+
def bubbleSort(array):
7+
8+
# loop to access each array element
9+
for i in range(len(array)):
10+
11+
# loop to compare array elements
12+
for j in range(0, len(array) - i - 1):
13+
14+
# compare two adjacent elements
15+
# change > to < to sort in descending order
16+
if array[j] > array[j + 1]:
17+
18+
# swapping elements if elements
19+
# are not in the intended order
20+
temp = array[j]
21+
array[j] = array[j+1]
22+
array[j+1] = temp
23+
24+
25+
list = [-2, 45, 0, 11, -9]
26+
27+
bubbleSort(list)
28+
print(list) #[-9, -2, 0, 11, 45]
29+
30+
# Optimized
31+
32+
def bubbleSort(array):
33+
34+
# loop through each element of array
35+
for i in range(len(array)):
36+
37+
# keep track of swapping
38+
swapped = False
39+
40+
# loop to compare array elements
41+
for j in range(0, len(array) - i - 1):
42+
43+
# compare two adjacent elements
44+
# change > to < to sort in descending order
45+
if array[j] > array[j + 1]:
46+
47+
# swapping occurs if elements
48+
# are not in the intended order
49+
temp = array[j]
50+
array[j] = array[j+1]
51+
array[j+1] = temp
52+
53+
swapped = True
54+
55+
# no swapping means the array is already sorted
56+
# so no need for further comparison
57+
if not swapped:
58+
break
59+
60+
list = [-2, 45, 0, 11, -9]
61+
62+
bubbleSort(list)
63+
print(list) #[-9, -2, 0, 11, 45]
64+

0 commit comments

Comments
(0)

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