《漫画算法--小灰的算法之旅》
每天学习一点数据结构,既是小灰的算法之旅,也是本人的算法之旅。
当前代码实现的是数组的指定位置插入数据的代码。
package com.java.array;
/**
* 向数组插入数据的思想
* 1、需要判断插入位置的下标是否是数组的正常范围之内
* 2、如果数组实际元素达到数组容量的上限,则对数组进行扩容
* 3、从右向左循环,将元素逐个向右移动,腾出的位置插入新的元素
*
* 当前程序:不允许随意插入任意位置的数据,不然报错。
*/
public class ArrayInsert {
private int[] arr;
private int size;
public ArrayInsert(int capacity) {
this.arr = new int[capacity];
this.size = 0;
}
public static void main(String[] args) throws Exception {
ArrayInsert aInsert = new ArrayInsert(4);
aInsert.insert(0, 3);
aInsert.insert(1, 9);
aInsert.insert(2, 5);
aInsert.insert(3, 7);
aInsert.insert(2, 6);
aInsert.insert(1, 8);
aInsert.outArr();
}
/**
* @param index 插入的下标
* @param element 插入的元素
* @throws Exception
*/
private void insert(int index, int element) throws Exception {
if (index < 0 || index > size) {
throw new Exception("Out of Index");
}
if (size >= arr.length) {
resize();
}
for (int i = size - 1; i >= index; i--) {
arr[i + 1] = arr[i];
}
arr[index] = element;
size++;
}
public void resize() {
int[] newArr = new int[arr.length * 2];
System.arraycopy(arr, 0, newArr, 0, arr.length);
arr = newArr;
}
private void outArr() {
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
System.arraycopy()源码:
* @param src the source array. * @param srcPos starting position in the source array. * @param dest the destination array. * @param destPos starting position in the destination data. * @param length the number of array elements to be copied. * @exception IndexOutOfBoundsException if copying would cause * access of data outside array bounds. * @exception ArrayStoreException if an element in the <code>src</code> * array could not be stored into the <code>dest</code> array * because of a type mismatch. * @exception NullPointerException if either <code>src</code> or * <code>dest</code> is <code>null</code>. */ public static native void arraycopy(Object src, int srcPos,Object dest, int destPos,int length);