【问题标题】:Insertion sort Numerical插入排序数值
【发布时间】:2014-02-17 23:30:47
【问题描述】:

我有两个数组,一个是字符串,另一个是整数。 我必须使用插入排序来按数字顺序打印这个列表这是我到目前为止的代码

这些是数组:

String[]bn={"Cardinals","BlueJays","Albatross","Vultures","Crows","Mockingbirds","Condors","BaldEagles","Pigeons","RedHeadWoodPecker","Hummingbirds","Dodos"};


int[]bq={40,15,1,3,10,2,12,25,7,6,88,15};   

    public static void SortNumericalOrdernsert (String[] bn,int[] bq){
    for(int i=1;i<bq.length;i++){
        int next=bq[i];
        String y=bn[i];
        //find all the insertion location 
        //Move all the larger elements up
        int j=i;
        while(j>0 && bq[j-1]>next){
            bn[j]=bn[j-1];
            bq[j]=bq[j-1];
               j--;
        }
        //insert the element
        bq[j]=next;
        bn[j]=y;
    }

}}

我哪里做错了?

【问题讨论】:

  • “必须”是什么意思?这是作业吗?
  • 你有什么问题?结果不正确?碰撞?编译错误?

标签: java arrays sorting computer-science


【解决方案1】:

//已编辑

你想这样做吗?

public static void SortNumericalOrdernsert(String[] bn, int[] bq) {
    for (int i = 1; i < bq.length; i++) {
        int next = bq[i];
        // find all the insertion location
        // Move all the larger elements up
        int j = i;
        while (j > 0 && bq[j - 1] > next) {
            bq[j] = bq[j - 1];
            j--;
        }
        bq[j] = next;
    }
    for (int i = 1; i < bn.length; i++) {

        String y = bn[i];
        int j = i;
        while (j > 0 && isBigger(bn[j - 1], y)) {
            bn[j] = bn[j - 1];
            j--;
        }
        bn[j] = y;
    }
}

private static boolean isBigger(String left, String right) {
    return left.compareTo(right) > 0;
}

【讨论】:

  • 你的代码是按字母顺序排序的,它需要按数字排序。
  • 输出必须是:1,2,3,6,7,10,12,15,15,40,88
  • 有一个错误..抱歉我没有检查代码。这是你想要的吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-12
  • 2011-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多