Implement Data Structure-Implement Array

Foreword

Learn from the sea and work hard

Know the data structure, but the specific implementation of the data structure is not very clear?

Starting today, slowly implement the data structure in familiar Java language


data structure

What is a data structure?

A data structure is a way for a computer to store and organize data, and refers to a collection of data elements that have one or more specific relationships

The role of data structures

Since the data structure is the way to store and organize data, then there must be the following functions

  1. Ability to insert a data
  2. Ability to find a specific data
  3. Ability to delete a specific data
  4. Ability to access all data for other operations

Common data structures

Insert picture description here

Insert picture description here

These data structures have their own characteristics, I hope that in the next time, slowly implement them through Java

Start with the simplest array


Array knowledge

An array is used to store a collection of the same data type

Declare array

There are two ways to declare an array in Java

(1)

数据类型[] 数组名 = new 数据类型[数组长度];
int[] num = new int[5];

Note: [] can put the front and back of the array name, but putting the front is more standardized, it can better show that this is an array.
Note: The exact size of the array needs to be limited

(2)

数据类型[] 数组名 = {"数组元素1”,"数组元素2"...}
int[] array = {1,2,3}

Note: The size of the array is determined by the number of elements in the given array

Access array elements

The array has a subscript index, from 0 to the length of the array -1

When accessing an array, you can access it by subscript

Assignment to an array also needs to be assigned to a position in the array by subscript (but not beyond the boundary)

//初始化
int[] num = new int[3];
//赋值
num[0]= 1;
//访问第一个数据
System.out.println(num[0]);

Insert picture description here

num[3]= 4;

Out of bounds error: ArrayIndexOutOfBoundsException
Insert picture description here

Array traversal

The array will provide a length property to indicate the length of the array

Then we choose the traversal method: for, foreach, iterator to traverse the array

int[] a = new int[3];
System.out.println(a.length);

Implement array

The nature of the array has been shown earlier

To simulate the data structure through Java array, hope to achieve the following functions

  1. Insert data (whether the subscript value is passed in)
  2. Find data based on subscript
  3. Delete data based on subscript
  4. Provide the length property to traverse
  5. Modify value

Here is a simple implementation of the int array data structure, and does not consider repeating elements

public class MyArray {
    //定义一个数组
    private int[] intArray;
    //数组实际长度
    private int realLength;
    //数组最大长度
    private int length;
    //构造一个数组
    public MyArray(int arrayLength){
        realLength = 0;
        length = arrayLength;
        intArray = new int[length];
    }
    //获得数组真实长度
    public int size(){
        return realLength;
    }
    //添加元素,返回成功与否
    public boolean add(int value){
        //数组满了
        if (realLength == length){
            System.out.println("数组满了,添加失败");
            return false;
        }
        else {
            //默认往数组尾添加数据
            intArray[realLength] = value;
            //真实长度+1
            realLength++;
        }
        return true;
    }
    //根据下标添加元素,返回成功与否
    public boolean add(int index,int value){
        //数组满了
        if (realLength == length){
            System.out.println("数组满了,添加失败");
            return false;
        }
        //越界
        if (index < 0 && index > length - 1){
            throw new ArrayIndexOutOfBoundsException();
        }
        //如果是替换
        if (index < realLength) {
            intArray[index] = value;
        }
        //如果是添加
        else {
            intArray[index] = value;
            realLength++;
        }
        return true;
    }
    //根据下标获取元素
    public int get(int index){
        //越界
        if (index < 0 && index > realLength - 1){
            throw new ArrayIndexOutOfBoundsException();
        }
        return intArray[index];
    }
    //遍历显示
    public void show(){
        for (int i : intArray){
            System.out.print(i+" ");
        }
    }
    //根据元素查找元素下标
    public int find(int value){
        int index = -1;
        for (int i = 0 ; i < realLength ; i++){
            if (i == value){
                index = i;
                break;
            }
        }
        return index;
    }
    //根据具体元素值删除元素
    public boolean delete(int value){
        //先查找该元素的下标
        int index = find(value);
        //如果没找到
        if (index == -1){
            return false;
        }
        else {
            deleteMethod(index);
            return true;
        }
    }
    //根据下标删除元素
    public boolean deleteByIndex(int index){
        //越界
        if (index < 0 && index > realLength - 1){
            throw new ArrayIndexOutOfBoundsException();
        }
        deleteMethod(index);
        return true;
    }
    //删除方法
    private void deleteMethod(int index){
        //如果是数组尾元素,直接-1
        if (index == realLength-1){
            realLength--;
        }
        //如果不是数组尾元素,需要将该元素后面的元素往前移动一位
        else {
            for (int i = index ; i < realLength-1 ; i++){
                intArray[i] = intArray[i+1];
            }
            realLength--;
        }
    }

    //修改元素
    public boolean modify(int oldValue,int newValue){
        int index = find(oldValue);
        if (index == -1){
            System.out.println("数据不存在");
            return false;
        }
        else {
            intArray[index] = newValue;
            return true;
        }
    }

}package com.company.Array;

public class MyArray {
    //定义一个数组
    private int[] intArray;
    //数组实际长度
    private int realLength;
    //数组最大长度
    private int length;
    //构造一个数组
    public MyArray(int arrayLength){
        realLength = 0;
        length = arrayLength;
        intArray = new int[length];
    }
    //获得数组真实长度
    public int size(){
        return realLength;
    }
    //添加元素,返回成功与否
    public boolean add(int value){
        //数组满了
        if (realLength == length){
            System.out.println("数组满了,添加失败");
            return false;
        }
        else {
            //默认往数组尾添加数据
            intArray[realLength] = value;
            //真实长度+1
            realLength++;
        }
        return true;
    }
    //根据下标获取元素
    public int get(int index){
        //越界
        if (index < 0 && index > length - 1){
            throw new ArrayIndexOutOfBoundsException();
        }
        return intArray[index];
    }
    //遍历显示
    public void show(){
        for (int i : intArray){
            System.out.println(i);
        }
    }
    //根据元素查找元素下标
    public int find(int value){
        int index = -1;
        for (int i = 0 ; i < realLength ; i++){
            if (i == value){
                index = i;
                break;
            }
        }
        return index;
    }
    //根据下标删除元素
    public boolean delete(int value){
        //先查找该元素的下标
        int index = find(value);
        //如果没找到
        if (index == -1){
            return false;
        }
        else {
            //如果是数组尾元素,直接-1
            if (index == realLength-1){
                realLength--;
            }
            //如果不是数组尾元素,需要将该元素后面的元素往前移动一位
            else {
                for (int i = index ; i < realLength-1 ; i++){
                    intArray[i] = intArray[i+1];
                }
                realLength--;
            }
            return true;
        }
    }
    //修改元素
    public boolean modify(int oldValue,int newValue){
        int index = find(oldValue);
        if (index == -1){
            System.out.println("数据不存在");
            return false;
        }
        else {
            intArray[index] = newValue;
            return true;
        }
    }
 
}

have a test:

class test{
public static void main(String[] args) {
        MyArray myArray = new MyArray(5);
        myArray.add(1);
        myArray.add(2);
        myArray.add(3);
        myArray.add(4);
        System.out.print("所有元素:");
        myArray.show();
        System.out.println();
        System.out.println("第四个元素是:"+myArray.get(3));
        System.out.println("元素2的下标是:"+myArray.find(2));
        System.out.println("数组的实际大小:"+myArray.size());
        myArray.deleteByIndex(3);
        System.out.print("删除元素后:");
        myArray.show();
        System.out.println();
        myArray.modify(2,5);
        System.out.print("修改元素:");
        myArray.show();
    }
}

Insert picture description here

At this point, the array data structure is realized, you can analyze the array


analysis

Array is the most basic data structure.
Array can complete the task of data structure, and it is very simple. Why doesn't it choose array to store data in actual application?

We can analyze the characteristics of the array

  1. Insert fast
    Unordered array insertion, just put data into the end of the array, just need to judge whether the array is full
    and if it is an ordered array, it also involves sorting (about sorting is implemented later), which makes insertion Not as fast
  2. Slow search
    Unordered array search will traverse the array until the element is found, of course, ordered array search can speed up the search speed according to the algorithm
  3. Delete slowly
    According to the element value deletion, you need to traverse to the element value. When deleting, in addition to the end of the queue, each deletion needs to shift the element behind
  4. Fixed size The size
    needs to be confirmed when the array is created. The size is fixed. If the setting is large, it may waste space.

In general, the performance of the array is too poor, so the actual use of the array is almost never used

Published 121 original articles · won 31 · views 7869

Guess you like

Origin blog.csdn.net/key_768/article/details/105451862