Skip to content

Instantly share code, notes, and snippets.

@echo-akash
Created October 5, 2017 16:02
Show Gist options
  • Save echo-akash/ee0089cf8595b7fd863f0d17d11da95b to your computer and use it in GitHub Desktop.
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
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);
}
}
@Shivam-Vishwasrao
Copy link

/* Finding the maximum and minimum value of an array */

package com.company;

public class Main {

public static void main(String[] args) {

    int[] a = {4,12,45,9,5};
    int max = 0;
    int min = max;

    for (int i = 0, j = 0; i<a.length; i++){
        if (a[i] > max){
            max = a[i];

        }
        if (a[j] < max){
            min = a[j];
        }

    }

    System.out.println("The maximum number in the array is: " + max);
    System.out.println("The minimum number in the array is: " + min);
}

}

Output:
The maximum number in the array is: 45
The minimum number in the array is: 4

@dhruvrajkotiya
Copy link

thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment