Bubble sort examples in python - python coding
Published at - Sep 08, 2021
In this lesson on python coding, we will talk about one of the fundamental algorithms in computer science for sorting Bubble Sort. Bubble sort algorithm is a very common question for python coding interviews. This article will help if you are preparing for a python coding interview, so let's try to write a simple python program to implement the bubble sort in python.
Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass of the list is repeated until the list is sorted.
These are some highlighted points about binary search algorithm
- Compares adjacent items and exchanges those that are out of order
- Time and Space complexity
- Worst complexity: n^2
- Average complexity: n^2
- Best complexity: n
- Space complexity: 1
- Look at the first number in the list.
- Compare the current number with the next number.
- Is the next number smaller than the current number? ...
- Move to the next number along in the list and make this the current number.
- Repeat from step 2 until the last number in the list has been reached.
- Step 1: Repeat Step Number 2 For i = 0 to N-1
- Step 2: Repeat For J = i + 1 to N - I
- Step 3: IF A[J] > A[i]
SWAP A[J] and A[i]
[END INNER LOOP]
[END OUTER LOOP
- Step 4: EXIT
Bubble sort example in python
for items in range(len(num_list)-1,0,-1):
for item in range(items):
if num_list[item] > num_list[item+1]:
temp = num_list[item]
num_list[item] = num_list[item+1]
num_list[item+1] = temp
Another bubble sort example in python
# Python program for implementation of Bubble Sort
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i]),
Both programs will print sort array as output.
Hi I'm Harendra Kumar Kanojiya. Currently I am FSD (Full-stack developer) and I have expertise with Angular ,PHP, Node JS, Laravel, Codeigniter and front end. Done few live projects and portfolio work in above.