4. Given a array of numbers, please write a method that can sort the numbers in the array from small to large.
时间: 2024-05-05 19:22:53 浏览: 90
Sure, here's an example implementation of the bubble sort algorithm in Python:
```python
def bubble_sort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already sorted
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 performs the bubble sort algorithm to sort the array in ascending order. The function returns the sorted array.
You can call this function by passing an array of numbers to it, like this:
```python
arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = bubble_sort(arr)
print(sorted_arr)
```
This will output:
```
[11, 12, 22, 25, 34, 64, 90]
```
阅读全文
相关推荐













