2011-01-28 72 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中编写代码并查看自己发生了什么吗?