Java:降序升级

时间:2014-08-01 13:35:11

标签: java

我和我的朋友做了这件事,想知道是否。

如果有人让我们将其更改为升序,我们如何才能改变条件?

    public class EXP2 {
        public static void main(String args[]){
        int nInputs;
                    int kth;
                            int temporarystorage;
                System.out.print("Number of inputs: ");
                nInputs = new Scanner(System.in).nextInt();
                int inputs[] = new int[nInputs];
                do{
                    System.out.print("Enter Kth Largest Number: ");
                    kth = new Scanner(System.in).nextInt();
                }
                while(!(kth>0&&kth<=nInputs));
                for(int o = 0; o < nInputs; o++){
                    System.out.print("Enter Input#: "+(o+1)+": ");
                    inputs[o] = new Scanner(System.in).nextInt();
                }
                for(int o = 0; o < nInputs; o++)
                    for(int i = o + 1; i < nInputs; i++)
                        if(inputs[o]<inputs[i]){
                temporarystorage = inputs[i];
                inputs[i] = inputs[o];
                inputs[o] = temporarystorage;
                        }
                System.out.println("Inputs in descending order: ");
                for(int i = 0; i < nInputs; i++)

                    System.out.print(inputs[i]+",");
                System.out.println("Kth position " + kth +" is "+inputs[kth-1]);


        }
    }

1 个答案:

答案 0 :(得分:0)

更改

        if(inputs[o]<inputs[i]){
            temporarystorage = inputs[i];
            inputs[i] = inputs[o];
            inputs[o] = temporarystorage;
        }

        if(inputs[o]>inputs[i]){
            temporarystorage = inputs[i];
            inputs[i] = inputs[o];
            inputs[o] = temporarystorage;
        }

将按升序排序。

或者如果它已经排序,只需按照user1071777的建议反向输出。