def bubble_sort
时间: 2023-08-27 19:04:58 浏览: 102
Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. Here's an example of bubble sort in Python:
```
def bubble_sort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# Swap if the element found is greater than the next element
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
```
This function takes an array `arr` as input and returns a sorted array using bubble sort. The outer loop runs `n` times, where `n` is the length of the array. For each iteration of the outer loop, the inner loop runs `n-i-1` times, where `i` is the current iteration of the outer loop. The inner loop compares adjacent elements and swaps them if they are in the wrong order. At the end of each iteration of the outer loop, the last `i` elements are already in place, so the inner loop doesn't need to check them again.
阅读全文