Giải Bài Insert New Element Into Sorted Array - Java OOP (LAB211 - FPT)

Hướng dẫn giải bài Insert New Element Java – lab211 FPT: nhập mảng, sắp xếp tăng dần, chèn phần tử mới đúng vị trí, không dùng sort lại.

Giới thiệu bài lab

Hello anh em! Tiếp tục series chiến LAB211 – Java cơ bản, hôm nay chúng ta cùng giải một bài tưởng như đơn giản mà vẫn đủ để “xoắn não” nhẹ: Chèn phần tử mới vào mảng đã sắp xếp.

Nghe thì đơn giản: nhập mảng → sắp xếp → chèn phần tử mới → in ra. Nhưng đề bài thêm một dòng cảnh báo như cảnh sát giao thông:

“Không được dùng sort lại sau khi chèn!”

Vậy là không được Arrays.sort() lần 2, phải tự chèn thủ công đúng chỗ. Hơi hack não nhẹ, nhưng lại rất đáng học để luyện tư duy làm việc với mảng.

Mục tiêu bài lab

  • Nhập mảng số nguyên từ bàn phím
  • Sắp xếp mảng tăng dần (duy nhất 1 lần)
  • Nhập thêm một phần tử mới
  • Chèn phần tử đó đúng vị trí để giữ thứ tự
  • Không sử dụng lại hàm sắp xếp sau khi chèn

Tại sao nên luyện bài này?

  • Giúp rèn tư duy thao tác mảng "thô" – không dùng thư viện hỗ trợ
  • Làm quen với việc xử lý dữ liệu tuyến tính
  • Thường xuất hiện trong các bài test đầu vào và bài tập Java cơ bản
  • Là nền tảng để học các cấu trúc dữ liệu phức tạp hơn như LinkedList

Đề bài gốc - Insert New Element Into Sorted Array

Title

Program to insert new element into an existing array.

Background Context

Insert new element into an existing array

Program Specifications

Create a program to insert new element into an existing array

Function details:

  1. Enter an integer array
  2. Sort array in ascending and display the sorted array on the screen
  3. Enter new integer value
  4. Add new value entered to the sorted array in ascending order and then display new array on the screen
  5. Finish program

Expectation of User interface:

The Program must have interface as below:

Please enter size of array: 5
Enter element[0]: 13
Enter element[1]: 3
Enter element[2]: 5
Enter element[3]: 10
Enter element[4]: 8
The array after sorting:
3 5 8 10 13
Please enter new value: 9
New array:
3 5 8 9 10 13

Guildeline

When insert new element into sorted array you don’t allow sorting the array again.

Source Code

📁 SE1905S01.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package se1905s01;

/**
 * S01 - Program to insert new element into an existing array.
 *
 * @author TruongNTCE180140
 */
public class SE1905S01 {

    /**
     * The main method
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // Create an instance of ArrayManager to handle array operations
        ArrayManager arrayManager = new ArrayManager();

        // Input the array elements from the user
        arrayManager.inputArray();

        // Sort the array in ascending order
        arrayManager.sortArray();

        // Display the sorted array
        System.out.println(arrayManager); // Automatically calls toString()

        // Insert a new value into the sorted array
        int newValue = MyLib.getIntegerInput("Please enter new value: ", "Error: Only integers can be entered.");
        arrayManager.insertNewValue(newValue);

        // Display the updated array
        System.out.println(arrayManager); // Automatically calls toString()
    }
}
📁 MyLib.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package se1905s01;

import java.util.Scanner;

/**
 * S01 - Program to insert new element into an existing array.
 *
 * @author TruongNTCE180140
 */
public class MyLib {
    // Create a Scanner object to receive input from the user.

    static Scanner scanner = new Scanner(System.in);

    /**
     * Method to input a positive integer from the user.
     *
     * @param message the message to display prompting the user for input.
     * @param errorMessage the message to display if the input is not valid
     * (i.e., not a positive integer).
     * @return the positive integer input by the user after passing validation.
     */
    public static int getPositiveInteger(String message, String errorMessage) {
        int number = 0; // Variable to store the user's input
        boolean isValidInput; // Flag for input validation

        do {
            try {
                isValidInput = true; // Assume input is valid
                System.out.print(message); // Prompt user for input
                number = Integer.parseInt(scanner.nextLine()); // Read and parse input

                if (number <= 0) {
                    System.out.println(errorMessage); // Error for non-positive integers
                    isValidInput = false; // Mark input as invalid
                }
            } catch (NumberFormatException e) {
                System.out.println(errorMessage); // Error for invalid number format
                isValidInput = false; // Mark input as invalid
            }
        } while (!isValidInput); // Repeat until valid input is received

        return number; // Return the valid positive integer
    }

    /**
     * Method to prompt the user for input and return a valid integer.
     *
     * @param message The message to display to the user when asking for input.
     * @param errorMessage The error message to display if the input is not a
     * valid integer.
     * @return The integer entered by the user.
     */
    public static int getIntegerInput(String message, String errorMessage) {
        int number = 0; // Variable to store the user's input
        boolean isValidInput; // Flag for input validation

        do {
            try {
                isValidInput = true; // Assume input is valid
                System.out.print(message); // Prompt user for input
                number = Integer.parseInt(scanner.nextLine()); // Read and parse input
            } catch (NumberFormatException e) {
                System.out.println(errorMessage); // Error for invalid number format
                isValidInput = false; // Mark input as invalid
            }
        } while (!isValidInput); // Repeat until valid input is received

        return number; // Return the valid integer
    }
}
📁 ArrayManager.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package se1905s01;

import java.util.Arrays;

/**
 * S01 - Program to insert new element into an existing array.
 *
 * @author TruongNTCE180140
 */
public class ArrayManager {

    private int[] array; // Array of integers
    private int flag = 0;  // Flag variable to indicate the display status
    private int size; // Size of the array

    /**
     * Method to input an array from the user.
     */
    public void inputArray() {
        // Get the size of the array from the user
        size = MyLib.getPositiveInteger("Please enter size of array: ", "Number of elements must be a positive integer.");
        array = new int[size]; // Initialize the array with the specified size

        // Loop through the array to get each element from the user
        for (int i = 0; i < array.length; i++) {
            array[i] = MyLib.getIntegerInput("Enter element[" + i + "]: ", "Error: Only integers can be entered."); // Input each element
        }
    }

    /**
     * Method to sort the array using the bubble sort algorithm.
     */
    public void sortArray() {
        // Use bubble sort to sort the array
        boolean swapped; // Flag to check if a swap occurred
        for (int i = 0; i < array.length - 1; i++) {
            swapped = false; // Reset swap flag for each pass
            // Move the largest element to the end
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    // Swap array[j] and array[j + 1]
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                    swapped = true; // Mark that a swap occurred
                }
            }
            // If no two elements were swapped, the array is already sorted
            if (!swapped) {
                break; // Exit the loop early if sorted
            }
        }
        flag = 1;
    }

    /**
     * Method to insert a new integer value into the sorted array.
     *
     * @param newValue The new integer value to be inserted.
     */
    public void insertNewValue(int newValue) {
        // Expand the array size to accommodate the new value
        array = Arrays.copyOf(array, size + 1);

        // Find the correct position to insert the new value
        int i;
        for (i = size; i > 0 && array[i - 1] > newValue; i--) {
            array[i] = array[i - 1]; // Shift elements to the right
        }

        // Insert the new value at the correct position
        array[i] = newValue;
        size++; // Increase the size of the array
        flag = 0;
    }

    /**
     * Returns the array as a formatted string.
     *
     * @return A string representation of the array.
     */
    @Override
    public String toString() {
        String message = (flag == 1) ? "The array after sorting: " : "New array: ";
        StringBuilder sb = new StringBuilder(message);
        for (int i = 0; i < array.length; i++) {
            sb.append(array[i]);
            if (i < array.length - 1) {
                sb.append(", ");
            }
        }
        return sb.toString();
    }
}

Open Source!
Hãy click vào từng folder để xem được code nhé anh em.

Ghi chú cho sinh viên FPT:

Mình có nhận giải lab thuê, hỗ trợ project, fix bug, training nhanh cho các môn ngành kỹ thuật từ toán đến lập trình phù hợp sinh viên FPT học đúng tiến độ.

Cam kết uy tín - đúng deadline - bảo mật tuyệt đối.

Liên hệ: Zalo.me/0973898830

TruongDevs

Kết luận

Bài này không quá khó nhưng rất tốt để luyện kỹ thuật xử lý mảng cơ bản - từ nhập, sắp xếp, đến chèn đúng vị trí mà không dùng lại hàm sort.

Nếu bạn đang học Java tại FPT hoặc luyện tay nghề backend Java thì đừng bỏ qua bài này. Và nếu bạn thấy hữu ích, nhớ lưu lại để dùng khi cần nhé.

Hẹn gặp lại trong các bài viết tiếp theo tại truongdevs.com.

Post a Comment