數據結構之數組代碼實現
package com.algorithm.array;
/**
* @author :Vimonster
* @date: 2019-12-04 22:58:13
* @slogan: 任時間再怎樣低頭呢喃,也要不揮淚後風雨兼程
* @description:
* 數據結構之數據組實現
**/
public class ArrayImpl {
private int size; //數組的長度
private int data[];
private int index; //當前已經存的數據大小
/**
* 數組初始化
* @param size
*/
public ArrayImpl(int size){
this.size = size;
data = new int[size]; //分配的內存空間{0,0,0,0,0}
index = 0;
}
/**
* 打印數組
*/
public void print(){
System.out.println("index:" + index);
for(int i = 0 ; i < index ; i++){
System.out.print(data[i] + " ");
}
System.out.println();
}
/**
* 給 loc 位置添加數據 n
* @param loc
* @param n
*/
public void insert(int loc,int n){ //時間複雜度 O(n);
if(index ++ < size){
for(int i = size - 1; i > loc ; i --){ //爲什麼不能寫size 0~size-1 如果loc是0 O(n),O(1)=>O(n)
data[i] = data[i - 1]; //把數據往後移一個
}
data[loc] = n;
}
//擴容 會把size*2 0.75
}
/**
* 刪除數組中 loc 位置的數據
* @param loc
*/
public void delete(int loc){ //O(n)
for(int i = loc ; i < size ; i++){
if(i != size - 1){ //怕越界所以加一個判斷
data[i] = data[i + 1];
}else{
data[i] = 0; //默認爲0 就是沒存數據的
}
}
index -- ;
}
/**
* 將數組中loc位置的數據更新爲n
* @param loc
* @param n
*/
public void update(int loc,int n){//O(1)
if(loc > data.length - 1){
System.out.println("更新的位置數組越界,請檢查你更新的位置");
}
data[loc] = n;
}
/**
* 獲取數組中 loc 位置的值
* @param loc
* @return
*/
public int get(int loc){ //O(1)
if(loc > data.length - 1){
System.out.println("獲取的位置數組越界,請檢查你獲取的位置");
}
return data[loc];
}
public static void main(String[] args) {
ArrayImpl array = new ArrayImpl(10);
array.index = 10;
array.data = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.println("原始數組爲:");
array.print();
array.delete(0);
System.out.println("刪除0位置後的數組爲: ");
array.print();
array.insert(0,0);
System.out.println("給0位置添加數據0後數組爲: ");
array.print();
array.update(2,10);
System.out.println("將2位置更新數據爲10後數組爲: ");
array.print();
}
}
========測試結果=======
原始數組爲:
index:10
0 1 2 3 4 5 6 7 8 9
刪除0位置後的數組爲:
index:9
1 2 3 4 5 6 7 8 9
給0位置添加數據0後數組爲:
index:10
0 1 2 3 4 5 6 7 8 9
給2位置更新數據爲10後數組爲:
index:10
0 1 10 3 4 5 6 7 8 9
Process finished with exit code 0