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

43 Comments

minmax Three ways to find minimum and maximum values in a Java array.

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<numbers.length;i++){
    if(numbers[i] < minValue){
	  minValue = numbers[i];
	}
  }
  return minValue;
}

These are very straight forward methods to get maximum or minimum value of an array but there is a more cleaner way to do this. More

article clipper vert Three ways to find minimum and maximum values in a Java array.
 

Sort numbers in Javascript array

4 Comments

numbers Sort numbers in Javascript array
Sorting an array in Javascript is a snap.
You create an array and then call sort() method on that array. The Javascript sort() method sorts an array in lexicographical order. This method is very useful in sorting alphanumeric values of an array.

However, sort() will not work if the array consists of numeric values. Because the alphabetical order of numbers is different from their numeric order the sorted array may not be in the order you are expecting. For example, in a dictionary sort the number “11″ would come before number “5″. This may not be the result that you are looking for.
Here is an example

var ages = new Array (23,6,2,16,48,9,6);
ages.sort();

The array will become (16,2,23,48,6,6,9)

Fortunately, the work around for this problem is quite simple.
More

article clipper vert Sort numbers in Javascript array