Bubble Sort with Python

Hey techies, I hope and wish u have a good day today, welcome to this week's article. Today, we are going to learn about "Bubble Sort" with python" . Hope you are loving my articles and I appreciate it if you show a response by commenting, liking or even sharing on your socials. I am focusing more on Python so I also suggest you to read my previous articles on Python.

  1. What is Bubble sort?

    Bubble sort is an simple and easiest sorting algorithim that works to arrange the elemnets in ordered manner,if they are in un-ordered manner.

  2. How it Works?

    It will compares each and every adjacent element with the current element and swaps based on (Increasing or Decreasing)order with "N" iterations.

  3. Time Complexity?

    As we use 2 for loop's [INNER AND OUTER] in this case each for loop check's "N" times about the condition until the iteration finishes.

  • Hence Time Complexity becomes O(N^2).

Let's Understand now:

#Present in un-sorted format
#Target : sorted -> Ascending order.
arr = [10,8,9,14,17]      #length of arr = 5

for i in range(0,len(arr)): #outer loop possibilities-[0,1,2,3,4].
    for j in range(0,len(arr)-1):  #inner loop possibilites-[0,1,2,3].
        if arr[j] > arr[j+1]:      #checking conditions.
            arr[j],arr[j+1] = arr[j+1],arr[j]  #SWAPS if conditon satisfies.

#IF U WANT TO CHECK EACH INNER LOOP [j's] ITERATION THEN REMOVE . 
            print("j's",j,"th iteration is :",arr)

print("Answer is:",arr)

# If U NEED SORT IN " DESCENDING ORDER " MEANS CHANGE ">" TO "<".
Output:
Answer is : [8, 9, 10, 14, 17]
  1. Advatages of Bubble sort ?

  • Stable Algorithim.

  • Bubble sort helps in sorting the algorithim by swapping its adjacent for "n" or "loop" times.

  • Easy to understand.

  • Doesn't require extra space in memory.

  1. Dis-advantages of Bubble sort ?

  • Time complexity of " O(N^2) " which is very slow.

  • Not suitable or stable for Large Data Set's**.**

I hope that u enjoyed reading the blog, However, I'm glad you will find the information helpful! If you enjoyed the blog, feel free to share it with others who might find it interesting. Sharing knowledge and information is always a great way to help others learn and grow.

"HAPPY LEARNING - HAPPY CODING"

Quote Of The Day~~

The world breaks everyone , and afterward, many are strong at the broken places.

-Ernest Hemingway

Did you find this article valuable?

Support Sohail's Blog by becoming a sponsor. Any amount is appreciated!