[자료구조/알고리즘] 배열(Array)

Vitabin·2025년 1월 15일
1

자료구조/알고리즘

목록 보기
1/11

1.배열

  • 특징
    - 많은 수의 데이터를 다룰 때 사용한느 자료구조
    - 각 데이터를 인덱스와 1:1 대응하도록 구성
    - 데이터가 메모리 상에 연속적으로 저장됨

  • 장점
    - 인덱스를 이용하여 데이터에 빠르게 접근 가능
    - 메모리에 연속적으로 저장되어 있기 때문에 빠르게 읽기 가능

  • 단점
    - 데이터 추가/삭제가 번거러움
    - 미리최대 길이를 정해서 생성해야함(메모리에 연속적으로 저장하기 때문)
    - 가변 길이 배열은 배열을 크기를 변경할 때마다 새로운 배열을 생성
    - 데이터 삭제 시, 인덱스를 유지하기 위해 빈 공간 유지

구현

import java.util.Arrays;

public class CustomArray {
    int[] arr;

    CustomArray(int size) {
        this.arr = new int[size];
    }

    public void insert(int idx, int data) {
        if (idx < 0 || idx > arr.length) {
            System.out.println("Index Error");
            return;
        }
        int[] clone = this.arr.clone();
        this.arr = new int[this.arr.length + 1];

        for (int i = 0; i < idx; i++) {
            this.arr[i] = clone[i];
        }

        for (int i = idx + 1; i < this.arr.length; i++) {
            this.arr[i] = clone[i - 1];
        }
        this.arr[idx] = data;
    }

    public void remove(int idx) {
        if (idx < 0 || idx > arr.length) {
            System.out.println("Index Error");
        }
        int[] clone = this.arr.clone();
        this.arr = new int[this.arr.length - 1];

        for (int i = 0; i < idx; i++) {
            this.arr[i] = clone[i];
        }

        for (int i = idx; i < this.arr.length; i++) {
            this.arr[i] = clone[i + 1];
        }
    }

    public static void main(String[] args) {
        CustomArray customArray = new CustomArray(3);
        System.out.println(Arrays.toString(customArray.arr));
        customArray.insert(0, 1);
        System.out.println(Arrays.toString(customArray.arr));
        customArray.insert(1, 2);
        System.out.println(Arrays.toString(customArray.arr));
        customArray.insert(2, 3);
        System.out.println(Arrays.toString(customArray.arr));

        customArray.remove(1);
        System.out.println(Arrays.toString(customArray.arr));
        customArray.remove(1);
        System.out.println(Arrays.toString(customArray.arr));
    }
}

0개의 댓글