Finding smallest element in an integer array in java using divide and conquor algorithm

时间:2015-07-28 16:06:43

标签: java

I tried to find the smallest element in an integer array using what i understood about divide and conquor algorithm. I am getting correct results. But i am not sure if it is a conventional way of using divide and conquor algorithm. If there is any other smarter way of implementing divide and conquor algorithm than what i have tried then please let me know it.

public static int smallest(int[] array){
       int i = 0;
       int array1[] = new int[array.length/2];
       int array2[] = new int[array.length - (array.length/2)];
       for(int index = 0; index < array.length/2 ; index++){
               array1[index] = array[index];
        }
        for(int index = array.length/2; index < array.length; index++){
               array2[i] = array[index];
                i++;
        }
        if(array.length > 1){
            if(smallest(array1) < smallest(array2)){
                return smallest(array1);
            }else{
                 return smallest(array2);
              }
        }
        return array[0];
   }

3 个答案:

答案 0 :(得分:1)

Your code is correct, but You can write less code using existing functions like Arrays.copyOfRange and Math.min

public static int smallest(int[] array) {
    if (array.length == 1) {
        return array[0];
    } 
    int array1[] = Arrays.copyOfRange(array, 0, array.length / 2);
    int array2[] = Arrays.copyOfRange(array, array.length / 2, array.length);
    return Math.min(smallest(array1), smallest(array2));        
}

Another point. Testing for the length == 1 at the beginning is more readable version. Functionally it is identical. From a performance point of view it creates less arrays, exiting as soon as possible from the smallest function.

It is also possible to use a different form of recursion where it is not necessary to create new arrays.

private static int smallest(int[] array, int from, int to) {
    if (from == to) {
        return array[from];
    }
    int middle = from + (to - from) / 2;
    return Math.min(smallest(array, from, middle), smallest(array, middle + 1, to));
}

public static int smallest(int[] array){
    return smallest(array, 0, array.length - 1);
}

This second version is more efficient because it doesn't creates new arrays.

答案 1 :(得分:1)

I don't find any use in using a divide and conquer in this paticular program.

Anyhow you search for the whole array from 1 to N, but in two steps

1. 1 to N / 2

2. N / 2 + 1 to N

This is equivalent to 1 to N.

Also you program check for few additional checks after the loops which aren't actually required when you do it directly.

int min = a[0];
for(int i = 1; i < arr.length; i++)
if(min < a[i])
  a[i] = min;

This is considered most efficient in finding out the minimum value.

When do I use divide and conquer

A divide and conquer algorithm works by recursively breaking down a problem into two or more sub-problems, until these become simple enough to be solved directly.

Consider the Merge Sort Algorithm. enter image description here

Here, we divide the problem step by step untill we get smaller problem and then we combine them to sort them. In this case this is considered optimal. The normal runs in a O(n * n) and this runs in O(n log n).

But in finding the minimum the original has O(n). So this is good.

Divide And Conquer

The book

Data Structures and Algorithm Analysis in Java, 2nd edtition, Mark Allen Weiss

Says that a D&C algorithm should have two disjoint recursive calls. I.e like QuickSort. The above algorithm does not have this, even if it can be implemented recursively.

答案 2 :(得分:0)

你在这里用代码做的是正确的。但是有更有效的方法来解决这个代码,我相信你已经知道了。

虽然可以将分而治之算法应用于此问题,但它更适合于复杂数据问题或通过将其分成较小的片段来理解困难的数据问题。一个主要的例子是'Tower of Hanoi'。

就您的代码而言,它是正确的。这是相同代码的另一个副本 -

export default Ember.TextField.extend({
 classNames: ['input-credit-card-number'],
 placeholder: '•••• •••• •••• ••••',
 autocomplete: 'cc-number',
 type: 'tel',


keyPress: function(e) {

  if (e.keyCode == 46 || e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 27 || e.keyCode == 13){
    return true;
  }

   var digit = String.fromCharCode(e.which);
   if (!/^\d+$/.test(digit)) {
     return false;
   }
      var el = this.$();
   if (hasTextSelected(el)) {
     return true;
   }

   var value = el.val() + digit;
   return inputValid(value);
   console.log(value);
 },

 value: computed('number', function(key, value) {
   var number = this.get('number');

   if (arguments.length > 1) {
     number = value;
     this.set('number', value);
   }

    return formatters.formatNumber(number);
  })

});

结果出来了 -

public class SmallestInteger {

public static void main(String[] args) {
    int small ;
    int array[] = {4,-2,8,3,56,34,67,84} ;
    small = smallest(array) ;
    System.out.println("The smallest integers is = " + small) ;
}

public static int smallest(int[] array) {
    int array1[] = new int[array.length/2];
    int array2[] = new int[array.length - (array.length/2)];

    for (int index = 0; index < array.length/2 ; index++) {
        array1[index] = array[index];
    }
    for (int index = array.length/2; index < array.length; index++) {
        array2[index - array.length/2] = array[index] ;
    }

    if (array.length > 1) {
        if(smallest(array1) < smallest(array2)) {
            return smallest(array1) ;
        }
        else {
            return smallest(array2) ;
        }
    }
    return array[0] ;

}

}