Implement Bubble Sort using Python
If you’re in a computer science background, widening your technical horizons is the best thing you should do. However, your programming skills matter the most and one must continuously keep sharpening these skills. And to become a better programmer in the future. Though there are multiple things to focus on, one specific area you must focus on is the world of data structures. Data structures in general are specific approaches to solve problems in such a way that computer resources get used minimum. In general, there are multiple data structures you can learn and implement as well. However, to keep things simple were going to start with some basic programs you must learn before moving on to complex algorithms. Therefore today we’re going to learn how to Implement Bubble Sort using Python.
What is Bubble Sort?
- Comes in the list of simplest data structures, Bubble Sort is the way of arranging elements in ascending order. The array is either sorted or is unsorted.
- Works by comparing adjacent elements in an array and swapping them, if required. This process continues till each element in an array gets sorted.
What’s The Approach?
- Consider array,
nwe want to implement Bubble Sort on. So firstly we’ll iterate a
forloop, with an iterative variable
0 to n-1.
- Next, inside the previous for loop, we’ll iterate a new for loop, with an iterative variable
0 to n-i-1.
- we’ll compare the element at iterating index with its next element from the array. If the comparing element is smaller, we’ll swap the elements.
Also Read: How To Print Hello World in Python
Python Program To Implement Bubble Sort
64, 34, 25, 12, 22, 11, 90
11 12 22 25 34 64 90
# Python program for implementation of Bubble Sort def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n): 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 arr = [64, 34, 25, 12, 22, 11, 90] bubbleSort(arr) print ("Sorted array is:") for i in range(len(arr)): print ("%d" %arr[i]),