Reputation: 23
I can't figure out how I can get the index location of the largest and smallest numbers in an array. Someone who can help me out here? My code:
int[] array = {4, 2, 7, 6, -3, -1, -2, 42, 0, -42, 9, -4, 5, -5, -6, -7, -8, -99, 42, 11, 20, 1, 2, 3};
int smallest = array[0];
int largest = array[0];
for (int i = 1; i < array.length; i++){
if (array[i] > largest) {
largest = array[i];
} else if (array[i] < smallest)
smallest = array[i];
}
System.out.println("Largest: " + largest);
System.out.println("Smallest: " + smallest);
I have already the largest and smallest numbers, but how can I find the index locations.
Upvotes: 0
Views: 308
Reputation: 1
I was able to came up with two answers :
ary.sort();
console.log(
`This is max ${ary[0]} of the numbers and here is ${
ary[-1]
} the min of the numbers list!`
);
_________________________________________________________________
` let ary = [8, 13, 2, 5, 44, 1, 5, 55];
let max = ary[0];
let min = ary[0];
let locationMax, locationMin;
for (i = 0; i <= ary.length; i++) {
if (ary[i] > max) {
max = ary[i];
locationMax = i;
} else if (ary[i] < min) {
min = ary[i];
locationMin = i;
}
}
console.log(
`This is the location of the max ${locationMax} so The second location number ${locationMin} is for min!`
);
Upvotes: -1
Reputation: 121
Create two more variables to store Largest index and smallest index, now whenever you assign a new value to smallest and largest in if-else statements also assign the value of i.
int smallestInd = 0;
int largestInd = 0;
for (int i = 1; i < array.length; i++){
if (array[i] > largest) {
largest = array[i];
largestInd = i;
} else if (array[i] < smallest)
smallest = array[i];
smallestInd = i;
}
Upvotes: 2
Reputation: 964
This should work
int[] array = {4, 2, 7, 6, -3, -1, -2, 42, 0, -42, 9, -4, 5, -5, -6, -7, -8, -99, 42, 11, 20, 1, 2, 3};
int si, smallest = array[si = 0];
int li, largest = array[li = 0];
for (int i = 1; i < array.length; i++) {
if (array[i] > largest) {
largest = array[li = i];
} else if (array[i] < smallest) {
smallest = array[si = i];
}
}
System.out.println("Largest: " + li);
System.out.println("Smallest: " + si);
or easier readable:
int[] array = {4, 2, 7, 6, -3, -1, -2, 42, 0, -42, 9, -4, 5, -5, -6, -7, -8, -99, 42, 11, 20, 1, 2, 3};
int si = 0, smallest = array[0];
int li = 0, largest = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] > largest) {
largest = array[i];
li = i;
} else if (array[i] < smallest) {
smallest = array[i];
si = i;
}
}
System.out.println("Largest: " + li);
System.out.println("Smallest: " + si);
Upvotes: 1