zoukankan      html  css  js  c++  java
  • 并归排序算法

      //并归排序算法  
     1
    static void Main(string[] args) 2 { 3 Random rd = new Random(); 4 int[] testData = new int[20]; 5 SetNewData(rd, testData); //初始化测试数组 6 Console.WriteLine("排序前"); 7 WriteDate(testData); //输出排序前数组 8 testData = Method(testData); //数组排序 9 Console.WriteLine(""); 10 Console.WriteLine("排序后"); 11 WriteDate(testData); //输出排序后数组 12 Console.Read(); 13 } 14 15 private static int[] Method(int[] noMethodData) 16 { 17 int[] result = new int[noMethodData.Length]; //左侧数组 18 int[] left, right, tempresult; //右侧数组 19 20 left = new int[noMethodData.Length / 2]; 21 right = new int[noMethodData.Length / 2]; 22 tempresult = new int[noMethodData.Length]; 23 24 if (noMethodData.Length <= 1) 25 return noMethodData; 26 if (noMethodData.Length % 2 == 1) 27 { 28 right = new int[noMethodData.Length / 2 + 1]; 29 } 30 for (int i = 0; i < noMethodData.Length; i++) 31 { 32 if (i < noMethodData.Length / 2) 33 { 34 left[i] = noMethodData[i]; //左侧数组赋值 35 } 36 else 37 { 38 right[i - noMethodData.Length / 2] = noMethodData[i]; //右侧数组赋值 39 } 40 } 41 left = Method(left); //左侧数组递归 42 right = Method(right); //右侧数组递归 43 result = SortMethod(left, right);//并归排序 44 45 return result; 46 } 47 48 private static int[] SortMethod(int[] left, int[] right) 49 { 50 int left_index = 0; 51 int right_index = 0; 52 int restult_index = 0; 53 int[] result = new int[left.Length + right.Length]; 54 //合并两个数组,直到一个数组的末尾 55 while (left_index < left.Length && right_index < right.Length) 56 { 57 result[restult_index] = left[left_index]; 58 if (right[right_index] < left[left_index]) 59 { 60 result[restult_index] = right[right_index]; 61 right_index++; 62 } 63 else 64 { 65 left_index++; 66 } 67 restult_index++; 68 } 69 //将为合并到结果数组的数字添加到结果中 70 int[] tempData = left; //默认右侧合并完成,合并左侧 71 int startIndex = left_index; //设置合并启始位子 72 if (left_index >= left.Length) //如果左侧合并完成合并右侧 73 { 74 tempData = right; //设在待合并数组为右侧数组 75 startIndex = right_index; //设置合并启始位子 76 } 77 for (; restult_index < result.Length; restult_index++) 78 { 79 result[restult_index] = tempData[startIndex]; 80 startIndex++; 81 } 82 return result; 83 84 } 85 86 private static void WriteDate(int[] data) 87 { 88 Console.WriteLine("Data:"); 89 for (int i = 0; i < data.Length; i++) 90 { 91 Console.Write(data[i].ToString() + " "); 92 93 } 94 Console.WriteLine(); 95 96 } 97 98 private static void SetNewData(Random rd, int[] data) 99 { 100 for (int i = 0; i < data.Length; i++) 101 { 102 data[i] = rd.Next(1, 100); 103 System.Threading.Thread.Sleep(10); 104 } 105 106 }
    智者乐山山如画, 仁者乐水水无涯。 从从容容一杯酒, 平平淡淡一杯茶。
  • 相关阅读:
    二维凸包
    luogu_P1287 盒子与球
    luogu_P1993 小K的农场
    luogu_P1712 [NOI2016]区间
    luogu_P2444 [POI2000]病毒
    luogu_P2154 [SDOI2009]虔诚的墓主人
    20191005-T3-U91353 放射性
    编译原理 笔记2 词法分析
    DFA到等价正则表达式的转化
    软件分析笔记10 Soundiness
  • 原文地址:https://www.cnblogs.com/bingxueme/p/2501672.html
Copyright © 2011-2022 走看看