Created
October 5, 2017 16:02
-
-
Save echo-akash/ee0089cf8595b7fd863f0d17d11da95b to your computer and use it in GitHub Desktop.
Finding maximum and minimum elements in an Integer array using Divide and Conquer method in Java
This file contains hidden or 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
import java.util.Scanner; | |
public class MaxMinDC { | |
static Scanner sc = new Scanner(System.in); | |
static int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE; | |
static int a[]; | |
static int size; | |
static void MaxMin(int i, int j) | |
{ | |
int max1, min1, mid; | |
if(i==j) | |
{ | |
max = min = a[i]; | |
} | |
else | |
{ | |
if(i == j-1){ | |
if(a[i] < a[j]){ | |
max = a[j]; | |
min = a[i]; | |
} | |
else{ | |
max = a[i]; | |
min = a[j]; | |
} | |
} | |
else{ | |
mid = (i+j)/2; | |
MaxMin(i, mid); | |
max1 = max; | |
min1 = min; | |
MaxMin(mid+1, j); | |
if(max < max1) max = max1;//updating here | |
if(min > min1) min = min1; | |
} | |
} | |
} | |
public static void inputArray() | |
{ | |
for(int i=0; i< size; i++){ | |
a[i] = sc.nextInt(); | |
} | |
} | |
public static void main(String[] args) { | |
System.out.println("Enter the size of the array: "); | |
size = sc.nextInt(); | |
a = new int[size]; | |
inputArray(); | |
MaxMin(0, size-1); | |
System.out.println("Max value: "+max+"\nMin value: "+min); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
/* Finding the maximum and minimum value of an array */
package com.company;
public class Main {
}
Output:
The maximum number in the array is: 45
The minimum number in the array is: 4