2015-07-10 82 views
0
input: 
4 
22 96 12 49 

output: 
2 4 1 3 

我在輸出中想要的是根據輸入的學生排名。如何根據學生的排名打印數字

但是我現在想直到現在出錯了。

int count=0; 
Scanner sc =new Scanner(System.in); 
System.out.println("enter a number"); 
int a =sc.nextInt(); 
long[] b=new long[a]; 
for (int i = 0; i < a; i++) { 
    b[i]=sc.nextLong(); 
}  
Arrays.sort(b); 
for (int j = a-1; j >= 0; j--) { 
    System.out.println(b[j]); 
    count++; 
    System.out.println(count); 
} 
+0

's []'在哪裏? –

+0

's []'應該是'b []',我認爲它是一個錯字。 –

回答

0

你可以從實用程序Arrays獲得幫助Java有!使用indexOfbinarySearch等來查找數組中給定元素的索引。

Scanner sc =new Scanner(System.in); 
    System.out.println("enter a number"); 
    int a =sc.nextInt(); 
    long[] b = new long[a]; 
    for (int i = 0; i < a; i++) { 
     b[i]=sc.nextLong(); 
    }  
    long[] tem = new long[a]; 
    System.arraycopy(b, 0, tem, 0, a); 
    Arrays.sort(b); 

    for (int i = 0; i < a; i++) { 
      int res = java.util.Arrays.binarySearch(b, tem[i]); 
     System.out.print(res + 1 + " "); 
    } 

這套程序是:

input: 
4 
22 96 12 49 

output: 
2 4 1 3 

看,如果陣列是沒有排序:

java.util.Arrays.asList(theArray).indexOf(value) 

如果數組進行排序,你可以使用性能二進制搜索:

java.util.Arrays.binarySearch(theArray, value) 
+0

@感謝rakeb .... – lucky

0

您必須保持原始索引以打印您想要的方式。 而不是創建一個整數數組,創建一個'包裝'數組。所以即使在排序之後,您也知道元素的原始索引,因此您可以將其排名在正確的索引中。

 Class Wrapper{ 
      Int index; 
      Int value ; 
     } 

    Wrapper [] input; 
    For(int I=0; I< n ; I++){ 
      Int value = scan next value; 
      Input[i] = new Wrapper (I,value); 
    } 

    sort input based on value; // ascending order 

    Int[] output; 
    For(int I=0; I < input.length; I++){ 
     output[input[i].index] = i+1; // to start the rank from 1. 
    } 
    Print output array