Bubble_sort
时间: 2023-09-06 22:14:28 浏览: 94
Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent elements, and swapping them if they are in the wrong order. The pass through the list is repeated until the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list.
Here is an example implementation of bubble sort in Python:
```
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
```
This implementation iterates through the list `n-1` times, where `n` is the length of the list. In each iteration, it compares adjacent elements and swaps them if they are in the wrong order. After each iteration, the largest element of the remaining unsorted portion of the list "bubbles" up to its correct position.
Please let me know if you have any further questions!
阅读全文