常用的内部排序算法
简单选择排序、直接插入排序和冒泡排序、折半插入排序、希尔排序算法、快速排序算法(递归和非递归)、堆排序
运行结果:
python
输入数据15,5,6,7,8,9,10
[外链图片转存中…(img-60STknHj-1720750359076)]
[外链图片转存中…(img-QWNWapS5-1720750359078)]
[外链图片转存中…(img-fVhvkUVx-1720750359079)]
C语言
输入数据8 6 80 50 40
[外链图片转存中…(img-yKdnpElL-1720750359079)]
[外链图片转存中…(img-MlEA4ULs-1720750359080)]
[外链图片转存中…(img-D81R9SPg-1720750359080)]
代码
Python代码
import tkinter as tk
from tkinter import ttk
class SortAlgorithms:
def __init__(self):
self.comparisons = 0
self.moves = 0
def reset_counters(self):
self.comparisons = 0
self.moves = 0
def bubble_sort(self, arr):
self.reset_counters()
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
self.comparisons += 1
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
self.moves += 1
yield arr[:]
def selection_sort(self, arr):
self.reset_counters()
n = len(arr)
for i in range(n):
min_idx = i
for j in range(i + 1, n):
self.comparisons += 1
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
self.moves += 1
yield arr[:]
def insertion_sort(self, arr):
self.reset_counters()
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
self.comparisons += 1
arr[j + 1] = arr[j]
self.moves += 1
j -= 1
yield arr[:]
arr[j + 1] = key
self.moves += 1
yield arr[:]
def shell_sort(self, arr):
self.reset_counters()
n = len(arr)
gap = n // 2
while gap > 0:
for i in range(gap, n):
temp = arr[i]
j = i
while j >= gap and arr[j - gap] > temp:
self.comparisons += 1
arr[j] = arr[j - gap]
self.moves += 1
j -= gap
yield arr[:]
arr[j] = temp
self.moves += 1
yield arr[:]
gap //= 2
def quick_sort(self, arr):
self.reset_counters()
def _quick_sort(items, low, high):
if low < high:
pivot_index = self.partition(items, low, high)
yield from _quick_sort(items, low, pivot_index)
yield from _quick_sort(items, pivot_index + 1, high)
yield from _quick_sort(arr, 0, len(arr) - 1)
def partition(self, items, low, high):
pivot = items[(low + high) // 2]
left = low
right = high
while True:
while items