1.视频讲解原理
2.创建控制台应用
3.代码
using System;
namespace Sort
{
class Program
{
static void Main(string[] args)
{
int[] A = new int[30];
Random ra = new Random();
for (int i = 0; i < 30; i++)
{
A[i] = ra.Next(200);
}
Program ps = new Program();
ps.ShellSort(A);
Console.WriteLine("排序结果:");
foreach (int a in A)
{
Console.Write(a + " ");
}
bool isSorted = true;
for (int i = 0; i < A.Length - 1; i++)
{
if (A[i] > A[i + 1])
isSorted = false;
}
Console.Write(isSorted);
Console.ReadKey();
}
public void ShellSort(int[] A)
{
for (int gap = A.Length; gap > 0; gap/=2)
{
for (int i = gap; i < A.Length; i++)//这段代码和插入排序完全一样,只是把原来的增量1改为了gap
{
int temp = A[i];
int j = i - gap;
while (j>=0&&temp<A[j])
{
A[j + gap] = A[j];
j -= gap;
}
A[j + gap] = temp;
}
}
}
}
}