Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Swap max and min in array

import java.io.*;
import java.util.*;

public class Hello{
    public static int getMinIndex(int[] array){
    int minIndex = 0;
    for (int i = 1; i <= array.length - 1; i++){
        if (array[i] < array[minIndex]){
        minIndex = i;
        }
    }
    return minIndex;
    }
    
    public static int getMaxIndex(int[] array){
        int maxIndex = 0;
        for (int i = 1; i<array.length; i++){
            if (array[i] > array[maxIndex]){
                maxIndex = i;
            }
        }
        return maxIndex;
    }
    
    public static int[] swap (int[] array){
        int minIndex = getMinIndex(array);
        int maxIndex = getMaxIndex(array);
        int temp = array[minIndex];
        array[minIndex] = array[maxIndex];
        array[maxIndex] = temp;
        return array;
    }
    
    public static void main (String args[]){
        int[] array = {10,2,30};
        System.out.println(Arrays.toString(swap(array)));
    }
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.