我们以TZC 1283为例简单说明一下排序(含十大经典排序算法)的python实现方法和C实现方法。希尔排序原理请参见:https://www.cnblogs.com/chengxiao/p/6104371.html 或 https://www.runoob.com/w3cnote/shell-sort.html
原题链接:1283: 简单排序
python代码如下:
import math
# 希尔排序
def shell_sort(arr):
gap = 1
while gap < len(arr) / 3:
gap = gap * 3 + 1
while gap > 0:
for a in range(gap, len(arr)):
tmp = arr[a]
b = a - gap
while b >= 0 and arr[b] > tmp:
arr[b + gap] = arr[b]
b -= gap
arr[b + gap] = tmp
gap = math.floor(gap / 3)
return arr
T = int(input())
for i in range(T):
s = input().split()
lt = [int(x) for x in s]
lt1 = lt[::-1]
lt1.pop()
n = len(lt1)
shell_sort(lt1)
for j in range(n):
if j != n - 1:
print(lt1[j], end=' ')
else:
print(lt1[j])
C语言代码如下:
#include#include #define N 1010 void shell_sort(int arr[], int len) //希尔排序 { int gap, i, j; int temp; for(gap=len/2; gap>0; gap/=2) for(i=gap; i =0 && arr[j]>temp; j-=gap) arr[j+gap]=arr[j]; arr[j+gap]=temp; } } int main() { int m,n,i,j,t,a[N]={0}; scanf("%d",&m); while(m--) { scanf("%d",&n); memset(a,0,n); //初始化数组 for(i=0;i<=n-1;i++) //输入 scanf("%d",&a[i]); shell_sort(a,n); for(i=0;i<=n-1;i++) //输出 { if(i!=n-1) printf("%d ",a[i]); else printf("%dn",a[i]); } } return 0; }



