简体   繁体   中英

Reversing an sorting algorithm

I got this algorithm that sort int[] a from low to high.

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;
        }
    }
}
}

What i want to do is to reverse it, make it sort from high to low. I thought this would be a walk in the park doing something like this:

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;
            }
        }
    }
}

I was wrong, this apparently does nothing. Anyone willing to help?

Edit: Thx Jesper and Satya, it worked.

This is enough:

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;
        }
    }
}
}
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;
    }
    }
}
}

try this, instead of if(a[i] > a[j]) , make it if(a[i] < a[j])

It should be:

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

It needs to be -1 , as arrays go from 0 to length-1 , you previously started off at 0, thus you need to start off at the other side, ie length-1 .

You need to check >= 0 . If you check < length , it will go on forever, since it only gets smaller, so it will never be larger than length . If you compare against 0, it will stop as soon as it gets to the beginning of the array.

But just changing if(a[i] > a[j]) to if(a[i] < a[j]) would be a simpler fix .

Believe me you do not need to change the travering loop :). Sorting logic is hidden into if(a[i] > a[j]) . Simply change change if(a[i] > a[j]) to if(a[i] < a[j]) . It will work.

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;
        }
    }
}

this is a bubble sort algorithm , just change the comparator method will be ok

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

let other code untouched.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM