输入10个数字,应用希尔排序算法用c#实现
请用c#写出一个希尔排序算法,要求输入10个整数,输出排序结果。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ShellSorter
{
class Program
{
private static int[] myArray;
private static int arraySize;
public static void Sort(int[] a)
{
myArray = a;
arraySize = myArray.Length;
ShellSort(myArray);
}
public static void ShellSort(int[] myArray)
{
int i, j, increment;
int temp;
//分组开始为长度/2,接着继续/2
for (increment = myArray.Length / 2; increment > 0; increment /= 2)
{
for (i = increment; i < myArray.Length; i++)
{
temp = myArray[i];//第一次排序increment=5,a[5]与a[0]比较,如果a[5]小于a[0]则交换
//a[6]与a[1]比较,如果a[6]小于a[1]则交换...
//第二次排序increment=2,a[2]与a[0]比较,如果a[3]小于a[1]则交换
//a[3]与a[1]比较,如果a[3]小于a[1]则交换
for (j = i; j >= increment; j -= increment)
{
if (temp < myArray[j - increment])
myArray[j] = myArray[j - increment];
else break;
}
myArray[j] = temp;
}
}
}
public static void Main(string[] args)
{
int[] a = new int[] { 4, 2, 1, 6, 3, 6, 0, -5, 1, 1 };
Program.Sort(a);
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
}
}
}using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ShellSorter
{
class Program
{
private static int[] myArray;
private static int arraySize;
public static void Sort(int[] a)
{
myArray = a;
arraySize = myArray.Length;
ShellSort(myArray);
}
public static void ShellSort(int[] myArray)
{
int i, j, increment;
int temp;
//分组开始为长度/2,接着继续/2
for (increment = myArray.Length / 2; increment > 0; increment /= 2)
{
for (i = increment; i < myArray.Length; i++)
{
temp = myArray[i];//第一次排序increment=5,a[5]与a[0]比较,如果a[5]小于a[0]则交换
//a[6]与a[1]比较,如果a[6]小于a[1]则交换...
//第二次排序increment=2,a[2]与a[0]比较,如果a[3]小于a[1]则交换
//a[3]与a[1]比较,如果a[3]小于a[1]则交换
for (j = i; j >= increment; j -= increment)
{
if (temp < myArray[j - increment])
myArray[j] = myArray[j - increment];
else break;
}
myArray[j] = temp;
}
}
}
public static void Main(string[] args)
{
int[] a = new int[] { 4, 2, 1, 6, 3, 6, 0, -5, 1, 1 };
Program.Sort(a);
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
}
}
}
原创文章转载请注明出处:云飞扬IT的blog





