Java minimum in sorted

Three ways to find minimum and maximum values in a Java array of primitive types.

In Java you can find maximum or minimum value in a numeric array by looping through the array. Here is the code to do that.

public static int getMaxValue(int[] numbers) < int maxValue = numbers[0]; for(int i=1;i < numbers.length;i++)< if(numbers[i] >maxValue) < maxValue = numbers[i]; >> return maxValue; > public static int getMinValue(int[] numbers) < int minValue = numbers[0]; for(int i=1;i> return minValue; >

These are very straightforward methods to get the maximum or minimum value of an array but there is a cleaner way to do this.

Using Arrays.sort method to Find Maximum and Minimum Values in an Array

int[] nums=; Arrays.sort(nums); System.out.println(«Minimum = » + nums[0]); System.out.println(«Maximum EnlighterJSRAW» data-enlighter-language=»null»>public static int getMaximumValueUsingRecursion(int[] numbers, int a, int n)< return a>=numbers.length?n:Math.max(n,max(numbers,a+1,numbers[a]>n?numbers[a]:n)); > private static int getMinimumValueUsingRecursion(int[] numbers, int a, int n)

Here is an executable Java class demonstrating the use of all three methods.

import java.util.Arrays; public class MinMaxValues< public static void main (String args[])< int numbers[]= ; //Find minimum (lowest) value in array using loop System.out.println("Minimum Value = " + getMinValue(numbers)); //Find maximum (largest) value in array using loop System.out.println("Maximum Value = " + getMaxValue(numbers)); //Find minimum (lowest) value in array by sorting array System.out.println("Minimum Value = " + minValue(numbers)); //Find maximum (largest) value in array by sorting array System.out.println("Maximum Value = " + maxValue(numbers)); //Find minimum (lowest) value in array using recursion System.out.println("Minimum Value = " + getMinimumValueUsingRecursion(numbers,0,numbers[0])); //Find maximum (largest) value in array using recursion System.out.println("Maximum Value ezoic-pub-ad-placeholder-105">

So which method do you like the most?

56 Comments

I really appreciate the fact you take the time to write about something that others “assume” everyone knows. Quick useful posts such as this really help more people than you might imagine. Keep them coming. Bret’s last blog post..Friday Finds for 05/02/2008: Online RAID Space Calculation

Thanks for your code above, in my case, i have to find them from the list of integer input from keyboard.
Have you solutions help me. Best regards!

I am just surprised why your code has Case difference in the upper box and the lower boxes. Couldn’t get ther result that way

Interesting – but of course the sort does more than merely find the maximum and minimum, and also involves correspondingly more work. Obviously, this is most relevant when the operation is to be used many thousands of times a second.

Читайте также:  Html разметка web страниц блокнота

Your version of the straight iteration is a bit convoluted: int getMax(int[] numbers) <
int max= Integer.MIN_VALUE;
for (int i : numbers)
max = Math.max(max, i);
return max;
> And the straight iteration is in fact the most efficient method, as using sort uses n*log(n) time and the recursive variant uses more resources on the stack. […] the number the program then needs to print the largest and smallest values. I have written a post earlier that shows one way of finding largest and smallest numbers. That approach used Arrays but […]

teach me more about arrays cous i realy dont understand it…
help me.. im napoleon the great pretender..

Nice! help out alot but i have to remove the 36.public static int getMinValue(int[] numbers)< thanks !

Thank you very much for taking the time to post these methods. I must have gone through 3 different wordings of my search in google and 20 different websites before I found this website. The previous 20 websites were just forums full of non-helpful people that assume everyone knows this and use lots of jargon that basically makes this far more complicated than needed.

Could you please tell me that how to find Max and Min Array through recursion (data structure) ? please send me the implementation …

in case you have to consider performance do not use sort, because this runs in O(n log n) time.
Collections.max should be prefered.

Used to get the Max and Min of integer array in one Iteration. public class TestMinMaxIntegerArray < /**
* @param args
*/
public static void main(String[] args) int[] xx = < -3, 0,10, 1, 1 >;
int min = 0;
int max = 0;
int tempMax = 0;
int tempMin = 0;
boolean flag = true;
for (int i = 0, j = 1; j < xx.length; i++, j++) if (xx[i] min) tempMin = min;
>
if (tempMax < max) tempMax = max;
> >
System.out.println(«MAX:» + tempMax + » » + «MIN:» + tempMin); > >

public static void main(String[] args) <
int[] xx = < -3, 0,10, 1, 1 >;
int min = 0;
int max = 0;
int tempMax = 0;
int tempMin = 0;
boolean flag = true;
for (int i = 0, j = 1; j < xx.length; i++, j++) <
if (xx[i] min) <
tempMin = min;
>
if (tempMax < max) <
tempMax = max;
> >
System.out.println(«MAX:» + tempMax + » » + «MIN:» + tempMin); >

Sorry, but I think I need some help here.. I can’t seems to get the minimum value but I can get the maximum value for my programme. Is this the complete code or something? Or you can somehow help me check through my programme on why I can’t get the desire result. int[] nums=<6,-1,-2,-3,0,1,2,3,4>;
Arrays.sort(nums);
System.out.println(“Minimum = ” + nums[0]);
System.out.println(“Maximum = ” + nums[nums.length-1]);

This is the working code: import java.io.*;
class maxx_minn
public static void main(String ags [ ])throws IOException
int i,max,min,num; BufferedReader br= new BufferedReader
(new InputStreamReader (System.in)); i=1;
max=0;
min=2^31-1; while(i <=10)
System.out.println(«Enter a number»);
num= Integer.parseInt (br.readLine());
if(maxnum)
min=num;
i++;
>
System.out.println(“THE MAXIMUM NUMBER IS:”+max);
System.out.println(“THE MINIMUM NUMBER IS:”+min);
>
>

please provide me the following source code of java Programming.
Create an Array of ten cells, store the value in the area at run time. Find the find the largest and smallest element.

create an array of ten cells, store the value in the area at run tim. Find the largest and smallest element.

import java.util.Scanner;
public class Array public static void main(String[]args)
int [][]marks=new int [2][2];
fillArray(marks,2,2);
max(marks,2,2);
>
public static void fillArray(int mmarks[][],int row ,int coloumn) int k=0;
Scanner input=new Scanner(System.in);
for (int i = 0; i < row ; i++)for(int j=0 ; j < coloumn ; j++)k=k+1;
System.out.println(«Enter marks»+k);
mmarks[i][j]=input.nextInt(); > > >
public static void max(int mnmarks[][],int nrow,int ncoloumn) int maxValue=mnmarks[0][0];
for (int i = 0; i < nrow ; i++)for (int j = 0 ; j maxValue) maxValue=mnmarks[i][j];
> >
> System.out.println(“highest=”+maxValue);
>
>

Читайте также:  Python usb core find

hi
i need some information about testing c programming
is anybody can help me what i have to do?
i have my program but i donot know where i have to test it
many thanks

Lets say if i want to show a maximum value , and there is an array of x[] = <10,20,30,40,40,40,30,20,10>;
assuming each data is month 1 to 9
i wan to show the maximum value is 40 in months (4,5,6)

java codes joptionpane maximum calculate to minimum then loop
please anybody to answer this problem. thanks give the complete codes.

Sorting just to find the min and max destroys your data integrity and takes longer to run than just searching. The sort will be O(n log n) and the search would have been O(n). The fact you destroy the original order of the data is not to be assumed okay.

Gr8 deal guyz.. I lyk diz stuffs.. Bt i want some 1 to help me with the code: to store 100 different numbers and calculate the difference between max nd Min of those numbers

import java.util.Scanner; class exam
public static void main(String[] args)
Scanner input = new Scanner(System.in); System.out.println(“Enter 5 numbers:”); int[] numbers = new int[5];
int sum = 0;
int max = numbers[0];
int min = numbers[0]; for(int i=0; i max) max = numbers[i];
>
else if (numbers[i] < min)min = numbers[i];
> > int average = sum / 5; System.out.println(«Sum: » + sum);
System.out.println(«Average: » + average);
System.out.println(«Max: » + max);
System.out.println(«Min: » + min );
>
> How come my «min» is always displaying «0»…Please can someone help me…Thanks

I must say it was hard to find your page in search results.
You write great articles but you should rank your
page higher in search engines. If you don’t know how
to do it search on youtube: how to rank a website Marcel’s
way

Yours is too tough.You guys can check mine..
import java.util.Scanner; public class Array < public static void Max() int i; int sum = 0;
double avg = 0;
Scanner input = new Scanner(System.in);
System.out.printf(“%s %s\n”, “Index”, “Value”);
int[] a = new int[4]; for (i = 0; i < a.length; i++) a[i] = input.nextInt(); sum += a[i]; > int d = Math.max(Math.max(a[0], a[1]), Math.max(a[2], a[3]));
int e = Math.min(Math.min(a[0], a[1]), Math.min(a[2], a[3])); avg = sum / i; System.out.printf(» sum is %d\nAvg is %f\nMaximum is %d\nMinimum is %d», sum, avg, d, e); > public static void main(String[] args) Array obj = new Array();
obj.Max();
> >

Thanks a ton. This is coming from a college student staying up at 1:42 am to do his CSC project. Welp, better get back to it…

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Источник

find minimum element in a sorted and rotated array

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.

In this post, we will see how to find minimum element in sorted and rotated array.

Problem:

You are given an sorted and rotated array as below:

If you note that array is sorted and rotated. You need to find minimum element in above array in o(log n) time complexity. You can assume that duplicates are not allowed in the array.

Solution:

You can use variant of binary search algorithm to solve above problem. You can use a property that if you divide array into two sorted sub arrays (, ), one will be sorted and other will have minimum element

Algorithm:

  • Compute mid i.e low+high/2.
  • Check if a[mid…high] is sorted
    • Minimum lies in left part, so low=mid+1;
    • Minimum lies in right part, so high=mid

    Java program to find minimum element in a sorted and rotated array :

    System . out . println ( «Minimum element in the array : » + findMinimumElementRotatedSortedArray ( arr , 0 , arr . length — 1 , 5 ) ) ;

    public static int findMinimumElementRotatedSortedArray ( int [ ] arr , int low , int high , int number )

    Was this post helpful?

    You may also like:

    Search for a range Leetcode – Find first and last position of element in sorted array

    Sort an array of 0s, 1s and 2s

    Check if it is possible to reach end of given Array by Jumping

    Check if Array Elements are Consecutive

    Find the local minima in array

    Sliding Window Maximum in java

    Count number of occurrences (or frequency) of each element in a sorted array

    Find subarrays with given sum in an array.

    Count 1’s in sorted Binary Array

    Find peak element in the array

    Share this

    Prev Maximum difference between two elements such that larger element appears after the smaller number

    Author

    Find first and last position of element in sorted array

    Search for a range Leetcode – Find first and last position of element in sorted array

    Table of ContentsApproach 1 (Using Linear Search)Approach 2 (Using Modified Binary Search-Optimal) In this article, we will look into an interesting problem asked in Coding Interviews related to Searching Algorithms. The problem is: Given a Sorted Array, we need to find the first and last position of an element in Sorted array. This problem is […]

    Sort an array of 0s, 1s and 2s

    Table of ContentsProblemSolution If you want to practice data structure and algorithm programs, you can go through Java coding interview questions. In this post, we will see how to sort an array of 0s, 1s and 2s.We have already seen a post on sort 0s and 1s in an array. Problem Given an array containing zeroes, […]

    Check if it is possible to reach end of given Array by Jumping

    Table of ContentsProblemSolution If you want to practice data structure and algorithm programs, you can go through Java coding interview questions.   Problem Given an array with positive integers as elements indicating the maximum length of a jump which can be made from any position in the array. Check if it is possible to have […]

    Check if Array Elements are Consecutive

    Table of ContentsProblemSolutionProgram to check if Array Elements are Consecutive If you want to practice data structure and algorithm programs, you can go through 100+ data structure and algorithm programs. In this post, we will see how to check if array elements are consecutive. Problem Given an array, we need to check if array contains […]

    Find the local minima in array

    Table of ContentsProblemSolutionNaive approachEfficient approach If you want to practice data structure and algorithm programs, you can go through Java coding interview questions. In this post, we will see how to find the local minima in the array. Problem An element is local minima if it is less than its neighbors. int [] arr =

    Sliding Window Maximum in java

    Table of ContentsProblemSolution If you want to practice data structure and algorithm programs, you can go through Java coding interview questions. In this post, we will see about Sliding Window Maximum in java Problem Given an Array of integers and an Integer k, Find the maximum element of from all the contiguous subarrays of size K. […]

    Источник

Оцените статью