Created
May 31, 2015 08:14
-
-
Save isqad/914c7ca5aacd7d87e803 to your computer and use it in GitHub Desktop.
Maximum integer from integer array of any length
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ru.cohab; | |
import java.io.InputStreamReader; | |
import java.io.BufferedReader; | |
import java.io.IOException; | |
public class App { | |
public static final int COUNT = 4; | |
public static void main(String[] args) throws Exception { | |
System.out.println("Enter " + COUNT + " numbers:"); | |
App app = new App(); | |
int[] test = app.inputNums(4); | |
System.out.println("Maximum: " + app.maximum(test)); | |
} | |
private int[] inputNums(int size) throws IOException { | |
int[] result = new int[size]; | |
InputStreamReader isr = new InputStreamReader(System.in); | |
BufferedReader br = new BufferedReader(isr); | |
for (int i = 0; i < size; i++) { | |
result[i] = Integer.parseInt(br.readLine()); | |
} | |
return result; | |
} | |
private int maximum(int a, int b) { | |
if (a < b) { | |
return b; | |
} | |
return a; | |
} | |
private int maximum(int[] numbers) { | |
int size = numbers.length; | |
if (size == 1) { | |
return numbers[0]; | |
} | |
if (size == 2) { | |
return maximum(numbers[0], numbers[1]); | |
} | |
int middle = size / 2; | |
int[] firstPart = new int[middle]; | |
int[] secondPart = new int[size - middle]; | |
for (int i = 0; i < middle; i++) { | |
firstPart[i] = numbers[i]; | |
} | |
for (int i = middle; i < size; i++) { | |
secondPart[i - middle] = numbers[i]; | |
} | |
return maximum(maximum(firstPart), maximum(secondPart)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment