Fastest way to find the largest number in an unsorted array? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Fastest way to find the largest number in an unsorted array?

9th Aug 2016, 10:59 AM
WPimpong
WPimpong - avatar
5 Answers
+ 2
Dunno about "fastest", but could just do a for loop that compares the index to a variable, if it's higher, it saves the index value as the variable value. The variable will keep changing as the numbers get higher until you're left with the biggest number in the array. public class Program { public static void main(String[] args) { int[] x = {2, 7, 9, 2, 6, 4, 13, 3, 7}; int compare = 0; for(int i : x){ if(i > compare){ compare = i; } } System.out.println(compare); } }
9th Aug 2016, 4:18 PM
James
James - avatar
+ 2
@SUCHIT it's an enhanced for loop. It cycles through the array with i being set as the value of the each index as it cycles through.
9th Aug 2016, 4:49 PM
James
James - avatar
+ 1
for(int i : x) means?
9th Aug 2016, 4:46 PM
SUCHIT YADAV
SUCHIT YADAV - avatar
0
What about using thread?
9th Aug 2016, 11:22 PM
WPimpong
WPimpong - avatar
0
use ".Max()" after the array nsme.
25th Dec 2016, 9:58 AM
Emad Tahmoures
Emad Tahmoures - avatar