簡體   English   中英

該算法有什么作用?

[英]What does this algorithm do?

明天參加考試,一個練習題問這個用偽代碼編寫的算法是做什么的。 有人可以幫忙嗎?

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

該算法采用一個整數數組(已排序或未排序),並輸出同一數組中索引高於當前位置大於當前索引位置值的項數。

例如

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

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

對於數組中的每個數字,此算法查找在其右邊的數字計數,這些計數形成一個大於或等於該數字的連續數字序列。

這是在幫助您自己完成考試並通過考試:您認為它能做什么? 如果通過A = [1、2、3]和n = 3,會發生什么? 如果您通過A = [3,2,1,0]和n = 3,會發生什么? 您能用Java / JavaScript / C#/ Python / Erlang編寫代碼,然后看看自己會發生什么嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM