Python不使用sort函数实现数组排序
时间: 2024-03-28 09:07:08 浏览: 161
可以使用其他排序算法来实现数组排序,比如冒泡排序、插入排序或选择排序等。以下是一个使用冒泡排序算法来排序数组的示例代码:
```python
def bubble_sort(arr):
n = len(arr)
# 遍历数组元素
for i in range(n - 1):
# 每次遍历找出最大的元素并放到末尾
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
# 测试示例
array = [5, 2, 8, 12, 3]
bubble_sort(array)
print(array)
```
这段代码使用了冒泡排序算法,每次遍历都将最大的元素冒泡到末尾。输出结果为 `[2, 3, 5, 8, 12]`,表示数组已成功排序。你可以根据需要选择不同的排序算法来实现数组排序。
相关问题
Python不使用sort函数实现数组排序利用数组长度和循环
可以使用数组长度和循环来实现一种简单的排序算法,比如选择排序。选择排序的基本思想是每次从未排序的部分中选择最小(或最大)的元素,放到已排序部分的末尾。
以下是一个使用选择排序算法来排序数组的示例代码:
```python
def selection_sort(arr):
n = len(arr)
# 遍历数组元素
for i in range(n):
# 假设当前元素为最小值的索引
min_index = i
# 在未排序部分中找到最小值的索引
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
# 将最小值与当前元素交换位置
arr[i], arr[min_index] = arr[min_index], arr[i]
# 测试示例
array = [5, 2, 8, 12, 3]
selection_sort(array)
print(array)
```
这段代码使用了选择排序算法,每次遍历找到未排序部分中的最小值,并将其与当前元素交换位置。输出结果为 `[2, 3, 5, 8, 12]`,表示数组已成功排序。这种方法利用了数组长度和循环的特性来实现排序功能。
python中如何用sort函数将数组从大到小排序
在Python中使用sort函数将数组从大到小排序,需要使用reverse参数。将reverse参数设置为True,即可将数组从大到小排序。例如:
```python
arr = [3, 6, 1, 8, 4]
arr.sort(reverse=True)
print(arr) # [8, 6, 4, 3, 1]
```
或者也可以使用sorted函数,该函数返回一个新的排好序的列表,原来的列表不会被修改。例如:
```python
arr = [3, 6, 1, 8, 4]
new_arr = sorted(arr, reverse=True)
print(new_arr) # [8, 6, 4, 3, 1]
```
阅读全文
相关推荐
















