首页 > c#, 数据结构与算法 > 输入10个数字,应用插入排序算法用c#实现

输入10个数字,应用插入排序算法用c#实现

输入10个数字,应用插入排序算法用c#实现
请用c#写出一个插入排序算法,要求输入10个整数,输出排序结果。
代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InsertSorter
{
class Program
{

private static int[] myArray;
private static int arraySize;
public static void Sort(int[] a)
{
myArray = a;
arraySize = myArray.Length;
InsertSort(myArray);

}
public static void InsertSort(int[] myArray)
{
int i, j, temp;
for (i = 1; i < myArray.Length; i++)
{
temp = myArray[i];//保存当前数据
j = i - 1;
//将数据插入有序表中,如果表中数据比该数据大
//那么就依次向后移动有序列表中的数据,直到找到第一个比它小的数据
//将它依次放在那个数据后面
while (j >= 0 && myArray[j] > temp)
{
myArray[j + 1] = myArray[j];
j--;
}
myArray[j + 1] = temp;//将数据插入有序列表中
}

}
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

本文链接: http://www.ajaxcn.net/archives/270

分类: c#, 数据结构与算法 标签: ,
一键分享到:新浪微博分享  分享到网易微博    转贴到开心网  推荐到豆瓣  分享到QQ空间    RSS订阅
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.