Algorithm learned with Python 17th: Sorting (bubble sort)

#Algorithm learned in Python

Introduction

Implement the basic algorithm in Python to deepen your understanding of the algorithm. Insertion sort is handled as the 17th bullet.

Bubble sort

Generally speaking, exchange sort refers to bubble sort. Compare the adjacent data in the list, and if the order of magnitude is different, arrange them. The image is shown below. image.png

Implementation

The code of the program according to the previous procedure and the output at that time are shown below.

code

bubble_sort.py


"""
2021/01/10
@Yuya Shimizu

Bubble sort
"""

def bubble_sort(data):
    """Bubble sort: Compares and sorts two data from the front."""   
    for i in range(len(data)):
        for j in range(len(data) - i -1):
            if data[j] > data[j+1]: #If the left side is larger
                data[j], data[j+1] = data[j+1], data[j] #Swap back and forth
                
    return data

if __name__ == '__main__':
    DATA = [6, 15, 4, 2, 8, 5, 11, 9, 7, 13]
    sorted_data = bubble_sort(DATA.copy())

    print(f"{DATA}  →  {sorted_data}")
output
[6, 15, 4, 2, 8, 5, 11, 9, 7, 13]  →  [2, 4, 5, 6, 7, 8, 9, 11, 13, 15]

It has been replaced successfully, but with this, even if comparison replacement is no longer necessary in the middle, it will always be repeated for the number of data. In order to omit that part, we added an operation to exit the repetition when the replacement is not performed after one round. The code and output are shown below.

code

bubble_sort_improved.py


"""
2021/01/10
@Yuya Shimizu

Bubble sort (improved version)
"""

def bubble_sort(data):
    """Bubble sort: Compares and sorts two data from the front. However, omit the parts that do not need to be replaced anymore."""
    change = True   #Assuming there is room for exchange
    
    for i in range(len(data)):
        if not change:  #Escape repeatedly without room for replacement
            break
        change = False  #Assuming there is no room for exchange
        for j in range(len(data) - i -1):
            if data[j] > data[j+1]: #If the left side is larger
                data[j], data[j+1] = data[j+1], data[j] #Swap back and forth
                change = True #There may be room for exchange
                
    return data

if __name__ == '__main__':
    DATA = [6, 15, 4, 2, 8, 5, 11, 9, 7, 13]
    sorted_data = bubble_sort(DATA.copy())

    print(f"{DATA}  →  {sorted_data}")
output
[6, 15, 4, 2, 8, 5, 11, 9, 7, 13]  →  [2, 4, 5, 6, 7, 8, 9, 11, 13, 15]

You can see that they are sorted in ascending order. This time, I want to compare before and after sorting, so I dare to store the result in the variable sorted_data, and the argument to the function is DATA.copy () by the copy function. The arguments are not affected. If you just want to sort, you don't need to do that, just use bubble_sort (DATA).

Bubble sort computational complexity

Finally, I will touch on the amount of calculation. Basically, as with selection sort, ** the amount of calculation is $ O (n ^ 2) $ ** when expressed in order notation. However, if no exchange occurs, only comparison (no exchange) is required, so ** $ O (n) $ **. The worst time complexity is still $ O (n ^ 2) $.

Impressions

Continuing from the last time, it wasn't that complicated. I learned that when swapping in a list at once, it is not necessary to temporarily save the value, just substitute it with a comma as follows. I think I got a big one.

data[j+1], data[j] = data[j], data[j+1]

I am looking forward to the sorting algorithm from the next time onward.

References

Introduction to algorithms starting with Python: Standards and computational complexity learned with traditional algorithms Written by Toshikatsu Masui, Shoeisha

Recommended Posts

Algorithm learned with Python 17th: Sorting (bubble sort)
Algorithm learned with Python 16th: Sorting (insertion sort)
Algorithm learned with Python 15th: Sorting (selection sort)
Algorithm learned with Python 19th: Sorting (heapsort)
Algorithm learned with Python 18th: Sorting (stack and queue)
Algorithm learned with Python 10th: Binary search
Algorithm learned with Python 5th: Fibonacci sequence
Algorithm learned with Python 9th: Linear search
Algorithm learned with Python 7th: Year conversion
Algorithm learned with Python 8th: Evaluation of algorithm
Algorithm learned with Python 4th: Prime numbers
Algorithm learned with Python 6th: Leap year
Algorithm learned with Python 12th: Maze search
Algorithm learned with Python 11th: Tree structure
Algorithm learned with Python 13th: Tower of Hanoi
Algorithm learned with Python 14th: Tic-tac-toe (ox problem)
Algorithm learned with Python 2nd: Vending machine
Algorithm learned with Python 3rd: Radix conversion
Python beginners challenge Cpaw CTF Q14 with bubble sort
Sorting image files with Python (3)
Sorting image files with Python
[Python3] Dijkstra's algorithm with 14 lines
Python beginners organize bubble sort
Bubble sort with fluffy animation
Implemented the algorithm of "Algorithm Picture Book" in Python3 (Bubble Sort)
[Python] Object-oriented programming learned with Pokemon
Perceptron learning experiment learned with Python
Python data structures learned with chemoinformatics
Efficient net pick-up learned with Python
1. Statistics learned with Python 1-1. Basic statistics (Pandas)
[Python] One-liner Stalin sort with 50 characters
Implementation of Dijkstra's algorithm with python
[Python] Reactive Extensions learned with RxPY (3.0.1) [Rx]
Python algorithm
Search the maze with the python A * algorithm
[Python] Sort
Python # sort
1. Statistics learned with Python 1-3. Calculation of various statistics (statistics)
Bubble sort
Implemented Stooge sort in Python3 (Bubble sort & Quicksort)
Bubble sort
Let's develop an investment algorithm with Python 1
I tried it with SymPy Live, Wolfram Alpha and google with reference to "Algorithm learned with Python 4th: Prime numbers".
1. Statistics learned with Python 1-2. Calculation of various statistics (Numpy)
Visualize the behavior of the sorting algorithm with matplotlib
Use Python and word2vec (learned) with Azure Databricks
1. Statistics learned with Python 2-1. Probability distribution [discrete variable]
Find the shortest path with the Python Dijkstra's algorithm
Solving the Python knapsack problem with the greedy algorithm
"Principle of dependency reversal" learned slowly with Python
FizzBuzz with Python3
Scraping with Python
Statistics with python
Python memorandum (algorithm)
Scraping with Python
Python with Go
Twilio with Python
Play with 2016-Python
Tested with Python
with syntax (Python)
Bingo with python