反转排序算法

时间:2013-10-28 09:03:15

标签: java algorithm sorting

我得到了这个算法,将int [] a从低到高排序。

public static void sortering(int[] a){
    int temp;               

    for(int i = 0; i < a.length; i++){
    for(int j = i + 1; j < a.length; j++){
        if(a[i] > a[j]){
            temp = a[j];
            a[j] = a[i];
            a[i] = temp;
        }
    }
}
}

我想要做的是扭转它,使其从高到低排序。我认为这将是在公园散步,做这样的事情:

public static void sorteringU(int[] a){
    int temp;

    for(int i = a.length; i < a.length; i--){
        for(int j = i - 1; j < a.length; j--){
            if(a[i] > a[j]){
                temp = a[j];
                a[j] = a[i];
                a[i] = temp;
            }
        }
    }
}

我错了,这显然什么也没做。 有谁愿意帮忙吗?

编辑:Thx Jesper和Satya,它有效。

5 个答案:

答案 0 :(得分:3)

这就够了:

public static void sorteringU(int[] a){
    int temp;               

    for(int i = 0; i < a.length; i++){
    for(int j = i + 1; j < a.length; j++){
        if(a[i] < a[j]){ // Change ">" to "<"
            temp = a[j];
            a[j] = a[i];
            a[i] = temp;
        }
    }
}
}

答案 1 :(得分:1)

public static void sortering(int[] a){
    int temp;               

    for(int i = 0; i < a.length; i++){
for(int j = i + 1; j < a.length; j++){
    if(a[i] < a[j]){
        temp = a[j];
        a[j] = a[i];
        a[i] = temp;
    }
    }
}
}

尝试此操作,而不是if(a[i] > a[j]),将其设为if(a[i] < a[j])

答案 2 :(得分:0)

应该是:

                 note -1   note condition change
                    V       V
for(int i = a.length-1; i >= 0; i--){
  for(int j = i - 1;    j >= 0; j--){

它必须是-1,因为数组从0变为length-1,之前从0开始,因此您需要从另一侧开始,即{{ 1}}。

您需要检查length-1。如果你检查>= 0,它会永远持续下去,因为它只会变小,所以永远不会大于< length。如果与0进行比较,它将在到达数组的开头时立即停止。

只需将length更改为if(a[i] > a[j])即可更简单

答案 3 :(得分:0)

相信我你不需要改变流动循环:)。排序逻辑隐藏在if(a[i] > a[j])中。只需将更改if(a[i] > a[j])更改为if(a[i] < a[j])即可。它会工作。

for(int i = 0; i < a.length; i++){
    for(int j = i + 1; j < a.length; j++){
        if(a[i] < a[j]){
            temp = a[j];
            a[j] = a[i];
            a[i] = temp;
        }
    }
}

答案 4 :(得分:0)

这是一个冒泡排序算法,只需更改比较器方法即可

    change it from if(a[i] > a[j]) to if(a[i] < a[j])

让其他代码不受影响。