Cách Sắp Xếp Một Mảng (Array) Và Chèn Một Phần Tử Vào Mảng ...

Bỏ qua nội dung

Giải pháp

Ví dụ sau minh họa cách sử dụng phương thức sort() và phương thức insertElement() được định nghĩa bởi người dùng để sắp xếp một Mảng (Array) và chèn một phần tử vào Mảng (Array) trong Java.

import java.util.Arrays; public class MainClass { public static void main(String args[]) throws Exception { int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 }; Arrays.sort(array); printArray("Sorted array", array); int index = Arrays.binarySearch(array, 1); System.out.println("Didn't find 1 @ " + index); int newIndex = -index - 1; array = insertElement(array, 1, newIndex); printArray("With 1 added", array); } private static void printArray(String message, int array[]) { System.out.println(message + ": [length: " + array.length + "]"); for (int i = 0; i < array.length; i++) { if (i != 0){ System.out.print(", "); } System.out.print(array[i]); } System.out.println(); } private static int[] insertElement(int original[], int element, int index) { int length = original.length; int destination[] = new int[length + 1]; System.arraycopy(original, 0, destination, 0, index); destination[index] = element; System.arraycopy(original, index, destination, index + 1, length - index); return destination; } }

Kết quả

Code trên sẽ cho kết quả sau:

Sorted array: [length: 10] -9, -7, -3, -2, 0, 2, 4, 5, 6, 8 Didn't find 1 @ -6 With 1 added: [length: 11] -9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8

Chia sẻ:

  • X
  • Facebook
Thích Đang tải... Tìm kiếm cho: Trang này sử dụng cookie. Tìm hiểu cách kiểm soát ở trong: Chính Sách Cookie
  • Theo dõi Đã theo dõi
    • CÙNG BẠN KHÁM PHÁ NGÔN NGỮ LẬP TRÌNH
    • Theo dõi ngay
    • Đã có tài khoản WordPress.com? Đăng nhập.
    • CÙNG BẠN KHÁM PHÁ NGÔN NGỮ LẬP TRÌNH
    • Theo dõi Đã theo dõi
    • Đăng ký
    • Đăng nhập
    • URL rút gọn
    • Báo cáo nội dung
    • Xem toàn bộ bài viết
    • Quản lý theo dõi
    • Ẩn menu
%d Tạo trang giống vầy với WordPress.comHãy bắt đầu

Từ khóa » Chèn Mảng Java