using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp3 { class Program { static LinkedList<int> sortArrayLink = new LinkedList<int>(); static void Main(string[] args) { //算法测试 在1KW条数据中取得最大的1W条 //生成数据 int[] randomInt = getRandomInt(10000000); int[] sortArray = randomInt.Take(10000).ToArray(); randomInt = randomInt.Skip(10000).ToArray(); sortArray = sortArray.OrderByDescending(u=>u).ToArray(); var item= sortArrayLink.AddFirst(sortArray[0]); for (int i = 1; i < sortArray.Length; i++) //生成链表 sortArrayLink.AddAfter(item,sortArray[i]); //开始排序 Stopwatch watch = new Stopwatch(); watch.Start(); int rpCount = 0; foreach (var num in randomInt) { rpCount++; Insert(num); } watch.Stop(); Console.WriteLine(watch.Elapsed); //foreach (var num in sortArrayLink) //{ // Console.WriteLine(num); //} Console.ReadLine(); } /// <summary> /// 获取指定长度的随机数据 /// </summary> /// <param name="length"></param> /// <returns></returns> static int[] getRandomInt(int length) { //开始循环获取数据 int[] randomInt = new int[length]; for (int i = 0; i < length; i++) { Random r = new Random(i); randomInt[i] = r.Next(length); } return randomInt; } /// <summary> /// 尝试插入到排序数组 /// </summary> /// <param name="sortArray">已经排序好的数组</param> /// <param name="insertNum">需要插入的数据</param> static void Insert(int insertNum) { var item = sortArrayLink.Last; if (insertNum < item.Value) return; var first = sortArrayLink.First; if (insertNum > first.Value) { sortArrayLink.AddBefore(first, insertNum); sortArrayLink.RemoveLast();//移除最后一个 return; } if (insertNum == first.Value) { sortArrayLink.AddAfter(first, insertNum); sortArrayLink.RemoveLast();//移除最后一个 return; } while (item.Next!= null) { if (item.Value < insertNum) { item = item.Next; continue; } sortArrayLink.AddAfter(item, insertNum); sortArrayLink.RemoveLast();//移除最后一个 return; } } } }
i5下运行
不计算生成数据时间 耗时0.27S 内存占用227MB