2011-01-28 98 views
0

明天參加考試,其中一個練習題詢問用僞代碼編寫的算法是幹什麼的。誰能幫忙?這個算法做什麼?

Algorithm ??? 
Input A: Array of Integers; n: Integer; 
Variables i, c: Integers; 

Begin 
    for i:=0 to n-1 do 
     c:=1; 
     while ((i+c)<n) and (A[i]<A[i+c]) do 
      c:=c+1; 
     od 
     output(i,A[i],c-1); 
    od 
End 
+0

@bananamana這麼說,你爲什麼不嘗試弄清楚自己?例如。嘗試運行它? – 2011-01-28 02:04:50

+0

注意詳細說明3參數output()函數的作用? – 2011-01-28 02:07:56

回答

2

該算法採用整數數組(排序或未排序),並輸出同一數組中項目的數量,其索引高於當前位置,這些索引大於當前索引位置值。

例如

升序的整數的手動排序後的數組:

public static void main(String[] args){ 
    // stores an array of integers 
    int [] myArray = {0,1,2,3}; 
    // assuming the length of array is n 
    int n = myArray.length; 
    // counter variables 
    int i,c; 
    // starting from array index 0 to the length of the array 
    for(i=0;i<(n);i++){ 
     c = 1; 
     while(((i+c)<n) && (myArray[i]<myArray[i+c])){ 
      c++; 
     } 
     System.out.println("index value..."+i+", myArray value..."+myArray[i]+", number of items in array with index greater than current with values greater than current..."+(c-1)); 
    } 

} 

將使輸出

 
index value...0, myArray value...0, number of items in array with index greater than current with values greater than current...3 
index value...1, myArray value...1, number of items in array with index greater than current with values greater than current...2 
index value...2, myArray value...2, number of items in array with index greater than current with values greater than current...1 
index value...3, myArray value...3, number of items in array with index greater than current with values greater than current...0 

降序整數的人工分類數組:

 
int [] myArray = {10,9,8}; 

輸出爲:

 
index value...0, myArray value...10, number of items in array with index greater than current with values greater than current...0 
index value...1, myArray value...9, number of items in array with index greater than current with values greater than current...0 
index value...2, myArray value...8, number of items in array with index greater than current with values greater than current...0 

一個整數數組都是一樣的:

 
int [] myArray = {1,1,1}; 

輸出將

 
index value...0, myArray value...1, number of items in array with index greater than current with values greater than current...0 
index value...1, myArray value...1, number of items in array with index greater than current with values greater than current...0 
index value...2, myArray value...1, number of items in array with index greater than current with values greater than current...0 
1

對於數組中的每一個號碼,該算法找到號碼在其右側形成數大於或等於該數字的連續序列的計數。

1

這裏是幫助你自己幫助你通過考試: 你認爲它有什麼作用? 如果你通過它A = [1,2,3]和n = 3,會發生什麼? 如果你通過它A = [3,2,1,0]和n = 3,會發生什麼? 你可以在Java/JavaScript/C#/ Python/Erlang中編寫代碼並查看自己發生了什麼嗎?