简体   繁体   中英

Why my sorting code does not work properly?

I have an array of ints and i need to: sort first half ascending and sort the other half descending. I don't know which is the reason that this won't work as i want.

        for(i = 0 ; i < array.length/2 - 1 ; i++){
            ok = false;
            for(j = i ; j < array.length/2 - 1 ; j++){
                if(array[j]>array[j+1]){
                    tempValue = array[j];
                    array[j] = array[j+1];
                    array[j+1] = tempValue;
                    ok = true;
                }
            }
            if(ok == false)
                break;
        }

        for(i = array.length/2 ; i < array.length - 1 ; i++){
            ok = false;
            for(j = i ; j < array.length - 1; j++){
                if(array[j]<array[j+1]){
                    tempValue = array[j];
                    array[j] = array[j+1];
                    array[j+1] = tempValue;
                    ok = false;
                }
            }
             if(ok == false)
                 break;
        }

Expected result: [4,1,2,5,6,8,7,9] - > [1,2,4,5,9,8,7,6].

Result in my code: [1,2,4,5,8,7,9,6].

There was multiple errors in your code. The major was ok=false when you're sorting the other half array.
The below code is working fine.

 public class MyClass {
        public static void main(String args[]) {
            int i,j,tempValue;
            int array[]= {4,1,2,5,3,6,8,7,10,9};
            boolean ok=true;

            for(i = 0 ; i < array.length/2  ; i++){
                    ok = false;
                    for(j = i ; j < array.length/2  ; j++){
                        if(array[j]>array[j+1]){
                            tempValue = array[j];
                            array[j] = array[j+1];
                            array[j+1] = tempValue;
                            ok = true;
                        }
                    }
                    if(ok == false)
                        break;
                }
                for(i = array.length/2 ; i < array.length  ; i++){
                    ok = false;
                    for(j = array.length/2 ; j < array.length - 1; j++){
                        if(array[j]<array[j+1]){
                            tempValue = array[j];
                            array[j] = array[j+1];
                            array[j+1] = tempValue;
                            ok = true;
                        }
                    }
                     if(ok == false)
                         break;
                }

        for(i = 0 ; i < array.length  ; i++){
        System.out.print(array[i]);
      }
        }
    }

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