当涉及到排序算法时,一些常见的排序算法包括插入排序、选择排序、冒泡排序、快速排序、归并排序和堆排序。以下是使用Python实现这些常见排序算法的示例代码:
- 插入排序(Insertion Sort):
definsertionSort(arr):for i inrange(1,len(arr)):
key = arr[i]
j = i -1while j >=0and arr[j]> key:
arr[j +1]= arr[j]
j -=1
arr[j +1]= key
- 选择排序(Selection Sort):
defselectionSort(arr):for i inrange(len(arr)):
min_idx = i
for j inrange(i+1,len(arr)):if arr[j]< arr[min_idx]:
min_idx = j
arr[i], arr[min_idx]= arr[min_idx], arr[i]
- 冒泡排序(Bubble Sort):
defbubbleSort(arr):
n =len(arr)for i inrange(n-1):for j inrange(n-i-1):if arr[j]> arr[j+1]:
arr[j], arr[j+1]= arr[j+1], arr[j]
- 快速排序(Quick Sort):
defquickSort(arr):iflen(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 quickSort(left)+ middle + quickSort(right)
- 归并排序(Merge Sort):
defmergeSort(arr):iflen(arr)<=1:return arr
mid =len(arr)//2
left = mergeSort(arr[:mid])
right = mergeSort(arr[mid:])return merge(left, right)defmerge(left, right):
result =[]whilelen(left)>0andlen(right)>0:if left[0]<= right[0]:
result.append(left.pop(0))else:
result.append(right.pop(0))
result.extend(left)
result.extend(right)return result
- 堆排序(Heap Sort):
defheapify(arr, n, i):
largest = i
l =2* i +1
r =2* i +2if l < n and arr[largest]< arr[l]:
largest = l
if r < n and arr[largest]< arr[r]:
largest = r
if largest != i:
arr[i], arr[largest]= arr[largest], arr[i]
heapify(arr, n, largest)defheapSort(arr):
n =len(arr)for i inrange(n //2-1,-1,-1):
heapify(arr, n, i)for i inrange(n -1,0,-1):
arr[i], arr[0]= arr[0], arr[i]
heapify(arr, i,0)
本文转载自: https://blog.csdn.net/weixin_42797483/article/details/132515418
版权归原作者 有梦想的咕噜 所有, 如有侵权,请联系我们删除。
版权归原作者 有梦想的咕噜 所有, 如有侵权,请联系我们删除。