Python, Bubble Sort, Data Structures - Python For Beginners






Get knowledge and concept regarding Bubble Sort in Python, Bubble Sort Implementation, Bubble sort algorithm, a Bubble sort program, etc. through this blog content.

Bubble Sort



Bubble sort is the simplest way of sorting algorithm that works by repeatedly swapping the adjacent elements until and unless they get in the correct order.
Example:

Bubble Sort Algorithm Explained

Bubble Sort Algorithm Explained



Here in the first class, the algorithm compares the first two consecutive pairs i.e. 5 and 1. 

Since 5 > 1 so swapping occurs. 

Again since 5 > 4 and 5 > 2 then swapping of these consecutive pairs is done. 

Now, since other consecutive pairs 5 and 8 are already in order so here swapping does not exist. 

After the end of the first class, we get,


Similarly, in the second class, firstly the first two consecutive pairs are taken i.e. 1 and 4 where no swapping exists. 

Then another consecutive pair 4 and 2 is taken where 4 > 2 so swapping occurs. 

Since the last 2 consecutive are arranged already in order, so swapping is not needed. 

After the second class, we sorted the algorithm in ascending order but since there was one swap that occurred in the second class so third class so be carried out because the definition says, the algorithm is sorted when one whole pass (iteration) contains no swap at all. 

The second pass gives,


Finally, the last(third) pass is examined which consists of no swap at all. 

So, we find the ascending sorted algorithm as,

Bubble Sort Pseudocode

algorithm BubbleSort

input list

sorted = False

while sorted == False:

num_swaps = 0

for i = 1 to list.count – 1

if list[i-1] > list[i] then

temp = list[i-1]

list[i-1] = list[i]

list[i] = temp

num_swaps = num_swaps + 1

end if

end for

if num_swaps == 0 then

sorted = True

else

sorted = False

end if

end while

output list

end BubbleSort

Algorithm

Step 1: Start
Step 2: Input a list
Step 3: Declare a variable sorted whose value is assigned as false
Step 4: Until the value of sorted is false it goes to step 5 else goes to step 12
Step 5: A new variable num_swaps is taken whose value is assigned as 0
Step 6: Until the value of i is from 1 to the total number of elements present in the list, go to step 7 else go to step 12
Step 7: Check whether the value of [i-1] > [i]. If it is true, then go to step 8 else go to step 12 
Step 8: Now, swap the value of list[i-1] and list[i] with the help of the new variable temp
Step 9: Initial num_swaps is added with one and the result is stored in a new variable called num_swaps. Then the value of num_swaps becomes 1.
Step 10: Check whether the value of num_swaps is zero. If num_swaps is 0 then go to step 11 or else go to step 4
Step 11: Now the value of sorted becomes true 
Step 12: A list in ascending order is printed out
Step 13: End

Code

#assuming a list

list_1 = [5,1,4,2,8]            

         

#printing the assumed list

print ("Before sorting the list in ascending order= “, list_1)

 

‘’’ iterating the outer loop with initialization in the range from i=0 to length of assumed list i.e.5’’’

for i in range(len(list_1)):

 

#another loop for checking the correct order of the consecutive pairs

    for j in range(len(list_1)-1):

 

‘’’ now comparing the two consecutive pairs and making them in the correct order by repeatedly swapping if needed’’’

        if list_1[j] > list_1[j+1]:

            temp = list_1[j]

            list_1[j] = list_1[j+1]

            list_1[j+1] = temp

 

#printing the list that is sorted in an ascending order

            print ("Ascending sorted list= ", list_1)

Output As:


The output of the Bubble sort code

Graphical representation of Bubble sort Algorithm:


Flowchart of Bubble Sort



Data Structures

Data Types in Python:

Each incentive (values) in python has a datatype. 

The classification of data that commands a compiler or an interpreter how you desire to access the particular data. 

In python programming, data type plays a vital role, we often need the data type to make our tasks easy and more understandable. 

There are many data types in Python. But here we are discussing the collection data types that include; 
  • List
  • Tuple
  • Dictionary, and 
  • Set
Let’s go through those data types in detail.

List

Lists are mutable data types that can be accessed through the index. 

A list is represented by square brackets, [ ]. 

A list can contain elements of the same or mixed type. 
Example;

                      list_1 = [1,4,6,8]                                    #a list of same type i.e. integer

          list_2 = [0,” a”,5.8,” Hello”, True]       #another list containing elements 

                                                                              of different types

As lists are mutable, so they can be accessed to whatever index we want. 

The position of the list can be changed. Like;

          L= [23,5,9,0]

          L [0] = [8]                                              #puts 8 at index 0  

          L is now [8,5,9,0]

We can add the element to the end of the list with L.append(element)    

L= [2,3,8,0]

L.append (6)

L is now [2,3,8,0,6] 

As we can add the element, in the same way we also can remove or delete the elements. 

For that we have remove (), del () and pop () functions.

          L= [1,2,3,4]                                           #a list of numbers

          L.remove (1)                                         #mutates L= [2,3,4]

          del (L [0])                                             #mutates L= [3,4]

         L.pop ()                                           #returns 0 and mutates L= [3]

Simply lists are also used for iteration using loops. 

We can convert lists to tuples as tuples are immutable and allow substantial optimization of the programs that we create.

Tuple

Tuples are the same as lists which are generally kept in a sequentially ordered form and are manipulated in different forms. 

Tuples are immutable and can’t be changed and cannot be removed or deleted. 

We can convert tuples to lists to make changes to the initial tuple, then convert them back to tuples. 

Since a tuple is an immutable list, so it cannot be changed in any way once it is created but it is defined in the same way as a list except the tuple is enclosed in parentheses instead of square brackets in the list. 

Tuples are zero-based same as of list. Tuples do not perform the functions like append, extend, remove, pop, del, and so on. 

But tuple has its own use as; tuples make our code safer if we write correct code that does not require to be changed. 

Also, they are faster than lists. Some of the tuples can be accessed as dictionary keys that contain immutable values like strings, numbers, etc. 

Slicing can also be carried out in tuples as lists. 
Example;

tuple_1 = ("tuple", "a", 2.0, 8)                            #representation of a tuple of different types


Dictionary

Dictionary is somehow unique from other collection data types. 

Other collection data types have only value as an element, but a dictionary has a (key: value) combination. 

Likewise list, dictionaries are also mutable, and items can be easily added or removed. Dictionaries are denoted by curly brackets { }. 

Dictionary is very simple to use. Dictionary’s key must be immutable, but values can be mutable or immutable type.
Example;

                    my_dict = { }                                                    #creating empty dictionary

          my_dict = {1: ‘sulav’, 2: ‘adhikari’}                  ‘’’dictionary with integer

                                                                                    keys and string values’’’

          my_dict = {‘fruit’: ‘Apple’, 2: [1,2,3]}                ‘’’dictionary with mixed

                                                                                    keys’’’

          my_dict = dict({1: ‘sulav’, 2: ‘adhikari’})            #using dict()

          my_dict = dict([(1, ‘sulav’), (2, ‘adhikar’)])        #from sequence having

                                                                                                each item as a pair

Set

Sets are known as an unordered collection of various items. 

They are not in ordered items. Each element in a set is separated by a comma inside the curly { } brackets. 

Sets always contain a unique element. 
Example:

                      set_1 = {1, 4, 0, 5}                                           #creating a set list

Sets can be modified. For adding two values in existing list, we have add () and update () function.

set_2 = {0, 8, 6, 7}                                          

set_2. update ({9})                                          ‘’’9 is added to set_2 and it

                      print (set_2)                                                    becomes {0,6,7,8,9}



There are altogether three methods to remove individual values from a set. They are 
  • discard ()
  • remove ()
  • pop () 
Set also performs its common operations using- union (), intersection (), difference () and symmetric difference () methods. 

Sets are also used in Boolean expressions.

Table with data related to the book store


In a python program, a list is the most appropriate collection data type for representing and storing the data. It is so because the list is mutable, and elements of a list can be changed. 

List not only contains the elements of the same type but also can contain elements of mixed types. 

Lists are easy to create and apply. The list has different operations for data storage. 

Data stored in the list can be extended, removed, and appended with the help of extending (), remove (), and append () functions respectively. 

Lists can be sliced, concatenated, and so on. 

We can also change the size of the lists. So being flexible and mutable, a list is a suitable collection datatype for representing and storing that data in Python programs.

Using the concept of list, the above-mentioned data in the table can be stored in python as;     
>>> book_id = ['B001', 'B002', 'B003']     
>>> name_of_the_book = ['Harry Potter', 'Start With Why', 'Programming with Python']
>>> price_of_the_book = ['$2', '$1.5', '$1.5'] 
>>> quantity_of_the_book = ['30', '10', '20']

Since the length of lists are equal so we can use 2D list which are more appropriate and is represented as;     
>>>book_store= [[‘book_id’, ‘book_name’, ‘book_price’0, ‘book_quantity’]
      ['B001', 'Harry Potter', '$2', '30']
      ['B002', 'Start With Why', '$1.5', '10']
      ['B003', 'Programming with Python', '$1.5', '20']]


Learning Reflection

Python in Today's World?
Python, being one of the best programming languages today has a great impact on today’s world. 

The reason behind the popularity of Python is that it is easy to code, understandable, easy to learn and memorize, simple, and so on. 

Companies all over the world mostly use this language for their betterment. 

Through the study of Python, there are a lot of scopes and opportunities like; web developer, data analyst, mobile application developer, programmer, and so on. 

The future of Python is too bright.

Post a Comment

0 Comments