But if it is required to search an unsorted array for the first N elements in order to find the maximum element then it is required to apply a different solution.
In order to find the maximum of first N elements of an unsorted array recursively following method can be used.
package basics; public class NumberUtils { public static int getMaxItemFromSubArray( int[] inArray, int index ) { if( index <= 0 || index>inArray.length ) return -1; if ( index == 1 ) { return inArray[0]; } int m = getMaxItemFromSubArray( inArray, index-1 ); if ( inArray[ index-1 ] > m) { return inArray[ index-1 ]; } else { return m; } } public static void main(String[] args) { int[] items = { 0, 5, 73, 33, 201, 3, 441 }; int maxItem = getMaxItemFromSubArray( items , 0 ); System.out.println("Max Item is = " + maxItem); maxItem = getMaxItemFromSubArray( items , 8 ); System.out.println("Max Item is = " + maxItem); maxItem = getMaxItemFromSubArray( items , 3 ); System.out.println("Max Item is = " + maxItem); maxItem = getMaxItemFromSubArray( items , 4 ); System.out.println("Max Item is = " + maxItem); maxItem = getMaxItemFromSubArray( items , 5 ); System.out.println("Max Item is = " + maxItem); maxItem = getMaxItemFromSubArray( items , 6 ); System.out.println("Max Item is = " + maxItem); maxItem = getMaxItemFromSubArray( items , 7 ); System.out.println("Max Item is = " + maxItem); } }
Create a NumberUtils.java file in your workspace.
When the main method inside the NumberUtils class executed it is going to print :
Max Item is = -1
Max Item is = -1
Max Item is = 73
Max Item is = 73
Max Item is = 201
Max Item is = 201
Max Item is = 441
No comments:
Post a Comment