Reputation: 193
In a number of array i need length till max value without using sort and
{6,8,2,7,10,3,1}
is it possible to return max-first minimum is that array(10-2=8)?
Upvotes: 1
Views: 176
Reputation: 305
A simple solution for it is the function Array.short, you can do that:
/*Code not tested*/
Arrays.sort(array);
System.out.println(array[0]); //min value
System.out.println(array[array.length-1]); //max value
You can see more about this function here: Java: Sort an array
Edit
If you can't sort you can use a algorithm here a good example http://www.java2novice.com/java-sorting-algorithms/bubble-sort/
Upvotes: 1
Reputation: 425013
The simplest code uses IntStream#summaryStatistics():
IntSummaryStatistics stats = IntStream.of(intArray).summaryStatistics();
int maxDiff = stats.getMax() - stats.getMin();
This approach has O(n) time complexity, which is better than O(n log n) time complexity of sorting the array.
There are faster O(n) algorithms that just calculate the max diff, but this approach is probably good enough for most purposes.
Upvotes: 0