python用列表实现插入排序算法,用index
时间: 2024-05-19 22:13:37 浏览: 43
def insert_sort(lst):
for i in range(1, len(lst)):
j = i - 1
temp = lst[i]
while j >= 0 and lst[j] > temp:
lst[j+1] = lst[j]
j -= 1
lst[j+1] = temp
return lst
# 测试
lst = [3, 5, 1, 8, 2, 9, 4, 7, 6]
print(insert_sort(lst)) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
相关问题
python折半插入排序,简单选择排序,快速排序算法代码实现
折半插入排序:
```python
def binary_insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
left, right = 0, i - 1
while left <= right:
mid = (left + right) // 2
if key < arr[mid]:
right = mid - 1
else:
left = mid + 1
for j in range(i - 1, left - 1, -1):
arr[j + 1] = arr[j]
arr[left] = key
return arr
```
简单选择排序:
```python
def selection_sort(arr):
for i in range(len(arr)):
min_index = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
return arr
```
快速排序:
```python
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
left = [x for x in arr[1:] if x < pivot]
right = [x for x in arr[1:] if x >= pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
```
这里分别实现了折半插入排序、简单选择排序、快速排序的代码。
用python实现排序算法
以下是Python实现的几种常见排序算法:
1. 冒泡排序
```python
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
```
2. 选择排序
```python
def selection_sort(arr):
n = len(arr)
for i in range(n-1):
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]
return arr
```
3. 插入排序
```python
def insertion_sort(arr):
n = len(arr)
for i in range(1, n):
j = i
while j > 0 and arr[j] < arr[j-1]:
arr[j], arr[j-1] = arr[j-1], arr[j]
j -= 1
return arr
```
4. 快速排序
```python
def quick_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr)//2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort(left) + middle + quick_sort(right)
```
5. 归并排序
```python
def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right)
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result += left[i:]
result += right[j:]
return result
```
以上是常见的几种排序算法的Python实现。
阅读全文