python 排序源码
时间: 2023-10-12 07:16:56 浏览: 87
排序源代码
以下是 Python 中常见的几种排序算法的源码实现:
1. 冒泡排序
```python
def bubble_sort(nums):
n = len(nums)
for i in range(n):
for j in range(n - i - 1):
if nums[j] > nums[j+1]:
nums[j], nums[j+1] = nums[j+1], nums[j]
return nums
```
2. 选择排序
```python
def selection_sort(nums):
n = len(nums)
for i in range(n):
min_index = i
for j in range(i+1, n):
if nums[j] < nums[min_index]:
min_index = j
nums[i], nums[min_index] = nums[min_index], nums[i]
return nums
```
3. 插入排序
```python
def insertion_sort(nums):
n = len(nums)
for i in range(1, n):
curr_val = nums[i]
j = i - 1
while j >= 0 and nums[j] > curr_val:
nums[j+1] = nums[j]
j -= 1
nums[j+1] = curr_val
return nums
```
4. 快速排序
```python
def quick_sort(nums):
if len(nums) <= 1:
return nums
pivot = nums[0]
left = [x for x in nums[1:] if x < pivot]
right = [x for x in nums[1:] if x >= pivot]
return quick_sort(left) + [pivot] + quick_sort(right)
```
5. 归并排序
```python
def merge_sort(nums):
if len(nums) <= 1:
return nums
mid = len(nums) // 2
left = merge_sort(nums[:mid])
right = merge_sort(nums[mid:])
return merge(left, right)
def merge(left, right):
result = []
i, j = 0, 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
```
阅读全文