Skip to Content
CoursesCSC122โปรแกรมเรียงแล้วสลับตัวเลข

โปรแกรมเรียงแล้วสลับตัวเลข

โจทย์

Write a Java program to sort a list of number and then swap according to the following conditions:

  1. If the size of list is odd number, then swap the first number with the number before the middle number and swap the last number with the number after the middle number as an example:

    • Input
    5 21.3 4 10 0.2 15 9
    • Sort
    0.2 4 5 9 10 15 21.3
    • Swap
    5 4 0.2 9 21.3 15 10
  2. If the size of list is even number, there will be two numbers in the middle. Then swap the first number with the left middle number, and swap the last number with the right middle number as example:

    • Input
    5 21.3 4 10 15 9
    • Sort
    4 5 9 10 15 21.3
    • Swap
    9 5 4 21.3 15 10

The first input is a size of a list. The second input is the list of numbers. Use datatype as double.

InputOutput
7
5 21.3 4 10 0.2 15 9
5.0 4.0 0.2 9.0 21.3 15.0 10.0
6
64 -399 -29 -790 475 854
-29.0 -399.0 -790.0 854.0 475.0 64.0

โค้ด

import java.util.Scanner; import java.util.Arrays; import java.util.ArrayList; public class Program { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int size = scanner.nextInt(); double[] array = new double[size]; for (int i = 0; i < size; i++) { array[i] = scanner.nextDouble(); } if (size <= 2) { for (double value : array) { System.out.print(value + " "); } return; } Arrays.sort(array); ArrayList<Double> result = rearrangeArray(array); for (double value : result) { System.out.print(value + " "); } } private static ArrayList<Double> rearrangeArray(double[] array) { ArrayList<Double> result = new ArrayList<>(); int size = array.length; int mid = size / 2; int leftMid = mid - 1; int rightMid = size % 2 == 0 ? mid : mid + 1; result.add(array[leftMid]); for (int i = 1; i < leftMid; i++) { result.add(array[i]); } result.add(array[0]); result.add(array[size - 1]); for (int i = rightMid; i < size - 1; i++) { result.add(array[i]); } if (size % 2 == 0) { result.add(array[rightMid]); } else { result.add(array[mid]); result.add(array[rightMid]); } return result; } }

คำอธิบาย

ปรับปรุงล่าสุด