Example of Python Bubble Sort Algorithm Program Code
Hi, this time I want to share a brief summary of the lecture material regarding the very simple bubble sort algorithm. OK, just take a look at the following explanation.
Understanding the Bubble Sort Algorithm
Bubble sort is a type of simple sorting algorithm, where if there is data, for example 3, 1, 4, 2, 8, the bubble sort function will sort the data from index 0 (first data) to the last index.
The bubble sort algorithm is named “bubble” because the way it works is similar to the way bubbles rise to the surface of water.
As the bubbles rise, the larger bubbles will pop and float to the top, while the smaller bubbles will remain below them. In this case, the elements in the list or larger array will “pop” (move) to the correct positions during the sorting process.
For example, the data above at index 0, namely number 3, turns out to be bigger than index 1, so in the bubble sort process it will become 1, 3, 4, 2, 8, that is, moving the larger number to the right and the small number to the left.
Next are the numbers 4 and 2, because 2 is smaller, move their position to 1, 3, 2, 4, 8. And so on if index data is still available in these numbers.
However, because in the example above there is no more data, the position remains as is. But this is only the first repetition, then we will do a second repetition so that the data is truly sorted from small to large.
Because in the data above it turns out that 3 > than 2, we can sort it into 1, 2, 3, 4, 8. The results of this second repetition make the data values from the array well sorted.
Example Bubble Sort Python Program Code
The following is an example of a simple bubble sort program code to sort random numbers 3, 1, 4, 2, 8 into order from smallest to largest:
def bubble_sort(x): for i in range(len(x) - 1, 0, -1): for j in range(i): if x[j] > x[j + 1]: temp = x[j] x[j] = x[j + 1] x[j + 1] = tempangka = [3, 1, 4, 2, 8]bubble_sort(angka)print(angka)
Closing
So, that’s an explanation of the bubble sort algorithm along with an example of the program code in the Python programming language. I hope it can help.