View Code of Problem 49


import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < a.length; i++) {
            a[i] = sc.nextInt();
        }
        int index = 0;
        int min = a[0];
        int temp = 0;
        for (int i = 0; i < a.length; i++) {
            if (a[i] < min) {
                index = i;
                min = a[i];
            }
        }
        temp = a[0];
        a[0] = min;
        a[index] = temp;

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

        for (int i = 0; i < a.length; i++) {
            if(i!=n-1)
                System.out.print(a[i]+ " ");
            else
                System.out.println(a[i]);
        }
    }
}

Double click to view unformatted code.


Back to problem 49