简体   繁体   English

递归算法查找数组中的最小元素

[英]recursive algorithm to find smallest element in array

I have some pseudo code for a recursive algorithm that finds the smallest number in an array. 我有一些用于递归算法的伪代码,该伪代码在数组中找到最小的数字。

Here is the algorithm. 这是算法。

Min(A[0..n - 1])
If n = 1 return A[0]
else
{ 
  temp <-- Min(A[0..n - 2])
  if temp <= A[n - 1]
     return temp
  else return A[n - 1]
}

One part I don't understand about this pseudo code is the line "temp <-- Min(A[0..n - 2])". 我对这个伪代码不了解的一部分是“ temp <-Min(A [0..n-2])”行。 Specifically why is it "n - 2" in the recursive call instead of "n - 1"? 具体说来,为什么在递归调用中它是“ n-2”而不是“ n-1”?

My other question is how I would implement that line in code. 我的另一个问题是如何在代码中实现该行。 I am using Java. 我正在使用Java。

Thanks in advance for any help. 在此先感谢您的帮助。

Because you array is indexed from 0 to n-1, inclusive. 因为数组的索引从0到n-1(含)。 You need to recurse on a sub-array that's one element smaller, hence n-2. 您需要递归一个小一个元素,因此n-2的子数组。

for your 1st question: 对于第一个问题:

since you are using a recursive algorithm, in order to solve the problem, you first have to solve the same problem with a smaller size. 由于您使用的是递归算法,因此为了解决该问题,您首先必须以较小的大小来解决相同的问题。 In this pseudocode, for finding the minimum of an array with the length of n, first the minimum of the same array with the size of n-1 is found and then the minimum is compared with nth element. 在此伪代码中,为了找到长度为n的数组的最小值,首先要找到大小为n-1的同一数组的最小值,然后将该最小值与第n个元素进行比较。 Your array is indexed from 0 to n-1 (which will make it's length = n) so for recursive call, you have to call the array from index 0 to n-2 (n-1 elements). 您的数组的索引从0到n-1(这将使其长度= n),因此对于递归调用,您必须从索引0到n-2(n-1个元素)调用数组。

for your 2nd question: This is how I would implement the code in Java: 对于您的第二个问题:这就是我将如何在Java中实现代码:

public class Minimum {
   public Minimum(int[] A) {
    findMin(A, 0, A.length-1);
}

public int findMin(int [] A, int start, int end){
    if (start== end-1)
        return A[0];
    else{
        int temp=findMin(A, start, end-1 );
        if (temp<=A[end]) 
            return  temp;
        else 
            return A[end];
    }
}

}

My other question is how I would implement that line in code. 我的另一个问题是如何在代码中实现该行。

If you are using an array. 如果使用数组。

// create an array with one less element.
A a2 = new A[a.length-1];
// copy the elements
System.arrayCopy(a,0,a2,0,a2.length);

If you are using a List 如果您使用清单

List<A> a2 = a.subList(0, a.length-1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM