【问题标题】:I try to make the merge sort go from bigger to little but it keep going from little to big我试图让合并排序从大到小,但它一直从小到大
【发布时间】:2020-08-09 10:43:31
【问题描述】:

试图从大到小我正在尝试使用排序和搜索合并排序:

import java.util.*;

class MergeSorter {
   public static void sort(int[] a) {  
      if (a.length <= 1) { return; }
      int[] first = new int[a.length / 2];
      int[] second = new int[a.length - first.length];
      for (int i = 0; i < first.length; i++) { 
         first[i] = a[i]; 
      }
      for (int i = 0; i < second.length; i++) { 
         second[i] = a[first.length + i]; 
      }
      sort(first);
      sort(second);
      merge(first, second, a);
   }

   private static void merge(int[] first, int[] second, int[] a) {  
      int iFirst = 0;
      int iSecond = 0;
      int j = 0;

      while (iFirst < first.length && iSecond < second.length) {  
         if (first[iFirst] < second[iSecond]) {  
            a[j] = first[iFirst];
            iFirst++;
         } else {  
            a[j] = second[iSecond];
            iSecond++;
         }
         j++;
      }
      while (iFirst < first.length) { 
         a[j] = first[iFirst]; 
         iFirst++; j++;
      }
      while (iSecond < second.length) { 
         a[j] = second[iSecond]; 
         iSecond++; j++;
      }
   }
}

public class MergeSortDemo888888 {
   public static void main(String[] args) {
      int [] myAry = { 3, 2, 6, 7 };
      System.out.println("myAry is " + Arrays.toString(myAry));
      MergeSorter.sort(myAry);
      System.out.println("myAry is sorted descendingly using selection sort: "+Arrays.toString(myAry));
   }
}

【问题讨论】:

  • 尝试在您选择的数组上干运行代码作为示例,看看为什么它是从小到大排序的。仔细查看merge 函数。一些帮助参考:geeksforgeeks.org/merge-sort

标签: java mergesort helper jgrasp


【解决方案1】:

merge 函数的第一个if 中,只需将此(first[iFirst] &lt; second[iSecond]) 更改为此(first[iFirst] &gt; second[iSecond])

【讨论】:

  • 天啊,非常感谢我是编码新手,这让我发疯了
  • 嘿,你不介意看我的第二个问题
  • 你的第二个问题在哪里?
  • 使用 LinkedList 处理一个数字 n = 1279。 4. 示例输出:数字是 1729 1, 7, 2, 9,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-29
  • 1970-01-01
  • 2013-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多