DEV Community

loading...

Day 44 Of 100DayOfCode: More About Algorithm

Durga Pokharel
A mathematics student learning to code.
・3 min read

This is my 44th day of #100DaysOfcode and #python. I continued to learn more about algorithm. Today I learned about bubble sort along with it's time complexity and space complexity.

Time complexity of an algorithm refers to the amount of time taken by an algorithm to run as a function of length of the input. Space complexity of an algorithm refers to the amount of space or memory taken by an algorithm to run as a function of the length of the input.

Bubble Sort

Bubble sort is the simple comparison based algorithm. In which each pair of adjacent element is compared and the position of element are interchanged if they are in wrong order.

def bubbleSort(A):
    for num in range(len(A)-1,0,-1):
        for i in range(num):
            if A[i] > A[i +1]:
                temp = A[i]
                A[i] = A[i +1]
                A[i + 1]  = temp
                print(f'Current array is {A}.')

A = [14, 33, 27, 35,10]
bubbleSort(A)
print(f'Sorted array is {A}.')
Enter fullscreen mode Exit fullscreen mode

Step 1

Starts with first two element 14, 33. Value 33 is greater than 14 so they are in right order. So it is already in sorted position. Now new array is
14 33 27 35 10

Step 2

Now we take two number 33 and 27. We find 33 is greater than 27 so their position interchange. New array look like
14 27 33 35 10

Step 3

Here 33 and 35 are in right position. We don't need to interchange their position.New array is
14 27 33 35 10

Step 4

We know that 10 is smaller 35. Hence they are not sorted. We interchange these values. We find that we have reached the end of the array. After one iteration, the array should look like
14 27 33 10 35
After second iteration it look like
14 27 10 33 35
After next iteration it look like
14 10 27 33 35
After one more iteration it look
10 14 27 33 35
Now our array is completely sorted.
Output of above code is given below

Current array is [14, 27, 33, 35, 10].
Current array is [14, 27, 33, 10, 35].
Current array is [14, 27, 10, 33, 35].
Current array is [14, 10, 27, 33, 35].
Current array is [10, 14, 27, 33, 35].
Sorted array is [10, 14, 27, 33, 35].
Enter fullscreen mode Exit fullscreen mode

Discussion (0)