'Swapping smallest and largest values in array

So I have to input a list of numbers stored in an array, specify how many int values that are to be stored in the array, and print out the original array plus the list of integers with the maximum and minimum values swapped.

I am not allowed to use library other than java.util.Scanner

So, if I input {1 2 3 4 5 6 7}, I'm supposed to get {7 2 3 4 5 6 1}. Everything in my code works except the swapping part, but I've managed to find the maximum and minimum values, I just don't know how to deal with them. Here's what I got:

public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        System.out.print("Enter array size (minimum size 7)? ");
        int size = in.nextInt();
        int [] array = new int [size];
        System.out.print("Enter " + size + " distinct integer values to store in the array: ");
        
        int i = 0;
        for (i = 0; i < size; i++) {
            array[i] = in.nextInt();
        }
            System.out.println();
            System.out.println("Original array:");
        
        for (i = 0; i < size; i++) {
            System.out.print(array[i]);
            System.out.print("\t");
        }
        System.out.println(" ");
        System.out.println(" ");
        System.out.println("Array after swapping the smallest and largest:");
        
        int large = array[0];
        int small = array[0];
        for (i = 0; i < size; i++) {
            if (array[i] > large) {
                large = array[i];
            }
        }
        for (i = 1; i < size; i++) {
            if (array[i] < small) {
                small = array[i];
            }
        }
        
        int temp = small;
        large = large;
        large = temp;
        
        for (i = 0; i < size; i++) {
            System.out.print(array[i]);
            System.out.print("\t");
        }
    
        
    }


Solution 1:[1]

Your main bug is here:

int small = 0;

should be

int small = Integer.MAX_VALUE;

But that alone won't fix your program. You also need to fix these:

  • for (i = 1; i < size; i++) should loop from 0, not 1.
  • if (array[small] < array[i]) should be if (array[small] > array[i])
  • if (array[big] > array[i]) should be if (array[big] < array[i])
  • array[small] = i should be small = i
  • array[big] = i should be big = i

I recommend replacing your code altogether with:

int small = Arrays.stream(array).min().getAsInt();
int big = Arrays.stream(array).max().getAsInt();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1