-4
    int [] x = new int[10];




    for(int i = 0; i<x.length;i++){
        x[i] = kb.nextInt();
    }

    int max = x[0];
    for(int i = 1;i<x.length;i++){
        if(x[i]>max){
            max = x[i];
        }

    }

    int min = x[0];
    for(int i = 1;i<x.length;i++){
        if(x[i]<min){
            min = x[i];
        }
    }

    x [max] = x [min];
    x [min] = x [max];

I want to change the index of the maximum value to that of the minimum value, but I need the actual index and not the maximum value, how do I do that?

Aaron
  • 5
  • 1
  • possible duplicate of [How to find index of int array in Java from a given value?](http://stackoverflow.com/questions/6171663/how-to-find-index-of-int-array-in-java-from-a-given-value) – mdewitt Sep 26 '14 at 01:26

2 Answers2

1

You need to keep another variable, example maxIndex, to hold the index that contains the maximum value is. Then, every time you update max (or min) update the maxIndex (or minIndex) variable with the index used to retrieve that max value.

This is how you would do it for the max:

int [] x = new int[10];

for(int i = 0; i < x.length; i++){
    x[i] = kb.nextInt();
}

int max = x[0];
int maxIndex = 0;
for(int i = 1; i < x.length; i++){
    if(x[i] > max){
        max = x[i];
        // This is where you update the index
        maxIndex = i
    }
}

You can apply the same prinicple to save the value for the min variable

mdewitt
  • 2,526
  • 19
  • 23
  • Thanks, I thought there would be a command to find which index a certain number was at, but that wouldn't make sense since there could be an infinite amount of instances that number appears. – Aaron Sep 26 '14 at 01:21
  • You could do `Arrays.asList(x).indexOf(max);` and it would find the first instance of the maximum value you found. But, you've already traversed the array when you looked for the value. No need to go through the array again. – mdewitt Sep 26 '14 at 01:24
0

Following application will be change indexes of minValue and maxValue of an array

public class Example {

public static void main(String[] args) {

    Scanner kb = new Scanner(System.in);

    int[] arr = new int[10];

    for (int i = 0; i < arr.length; i++) {
        arr[i] = kb.nextInt();
    }

    int maxIndex = 0;
    int minIndex = 0;

    for (int i = 0; i < arr.length; i++) {
        if (arr[maxIndex] < arr[i]) maxIndex = i;
        else if (arr[minIndex] > arr[i]) minIndex = i;
    }

    int temp = arr[maxIndex];
    arr[maxIndex] = arr[minIndex];
    arr[minIndex] = temp;

    for (int x : arr) System.out.print(x + "");
}

}