Skip to content

Commit 40920db

Browse files
committed
Bubble sort code added
0 parents  commit 40920db

File tree

5 files changed

+61
-0
lines changed

5 files changed

+61
-0
lines changed

.gitignore

Whitespace-only changes.

README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
#Intro
2+
3+
4+
### Primitive types or data structures in Python
5+
Integer, Float, Boolean, Char

Sorting/Bubble Sort/README.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Bubble Sort
2+
3+
**Bubble Sort** is an algorithm which is used to sort **N** elements that are given in a memory for eg: an Array with N number of elements. Bubble Sort compares all the element one by one and sort them based on their values.
4+
5+
It is called Bubble sort, because *with each iteration the smaller element in the list bubbles up towards the first place*, just like a water bubble rises up to the water surface.
6+
7+
Sorting takes place by stepping through all the data items one-by-one in pairs and comparing adjacent data items and swapping each pair that is out of order.
8+
![bubble sort demonstration](bubble-sort.png)

Sorting/Bubble Sort/bubble-sort.png

8.5 KB
Loading

Sorting/Bubble Sort/bubble_sort.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Python program for implementation of Bubble Sort
2+
3+
def bubbleSort(arr):
4+
n = len(arr)
5+
6+
# Traverse through all array elements
7+
for i in range(n):
8+
9+
# Last i elements are already in place, so the inner loops will run until it reaches the last i elements
10+
for j in range(0, n-i-1):
11+
12+
# traverse the array from 0 to n-i-1
13+
# Swap if the element found is greater than the next element
14+
if arr[j] > arr[j+1] :
15+
arr[j], arr[j+1] = arr[j+1], arr[j]
16+
17+
18+
def modifiedBubbleSort(arr):
19+
n = len(arr)
20+
21+
# Traverse through all array elements
22+
for i in range(n):
23+
# Taking a flag variable
24+
flag = 0
25+
# Last i elements are already in place
26+
for j in range(0, n-i-1):
27+
28+
# traverse the array from 0 to n-i-1
29+
# Swap if the element found is greater
30+
# than the next element
31+
if arr[j] > arr[j+1] :
32+
arr[j], arr[j+1] = arr[j+1], arr[j]
33+
# Setting the flag, if swapping occurs
34+
flag = 1
35+
36+
# If not swapped, that means the list has already sorted
37+
if flag == 0:
38+
break
39+
40+
# Main code
41+
arr = [64, 34, 25, 12, 22, 11, 90]
42+
43+
bubbleSort(arr)
44+
# modifiedBubbleSort(arr)
45+
46+
print ("Sorted array is:")
47+
for i in range(len(arr)):
48+
print ("%d" %arr[i]),

0 commit comments

Comments
 (0)