您的位置:首页 > 其它

【Data Structures】 3. ArrayList and Binary Search

2016-11-01 03:46 309 查看
ArrayList class has many methods:

add(object), add(index, object), set(index, object), get(index), remove(index), size()

Initial length of new ArrayList is 10. You can also set the initial ArrayList length on your own.

List<Integer> numbers = new ArrayList<Integer>(0);

The ArrayList used to implement the doubling-up policy. (In Java 6, there has been a change to be ((oldCapacity*3)/2+1).

public boolean add(E e) {
ensureCapacity(size + 1);
elementData[size++];
return true;
}

public void ensureCapacity(int minCapacity) {
modCount++;
int oldCapacity = elementData.length;
if (minCapacity > oldCapacity) {
Object oldData[] elementData;
int newCapacity = (oldCapacity * 3)/2 + 1;
if (newCapacity < minCapacity) {
newCapacity = minCapacity;
}
elementData = Arrays.copyof(elementData, newCapacity);
}
}


However, the removal in Java is not that efficient due to the nature of array. The ArrayList needs to shift many elements in the array EVERY TIME the remove(int index) or remove(Object o) method is called (except removing the last
element).
Also, those remove method calls do not reduce the length of the underlying array, which can be a concern interms of memory usage.

If you had any issue with unused memory, you need to manually call trimToSize() method to free up the memory.

Running time complexity analysis of add(E, e) method: adding a new element to the end of an array: Amortized Analysis

Adding a new element at the end of an array takes constant time: O(1). However, when the array is full and we still need to add a new element, we then need to create a new array whose length is twice bigger than that of the original
array AND copy all the elements of the old array into the new array.

List<Integer> numbers = new ArrayList<Integer>(4);

 Running time# of elementsArray lengthAllocated dollarsCostSaved dollarsBalance
number.add(1)1143122
number.add(2)1243124
number.add(3)1343126
number.add(4)1443128
number.add(5)55835-26
number.add(6)1683128
number.add(7)17831210
number.add(8)18831212
number.add(9)991639-66
We can conclue that add(E, e) method has amortized constant time by looking at allocated dollars per operation.

Binary Search

Prerequisite for the binary search: The array should already be ordered.

public static int binarySearch(int[] data, int key) {
int lowerBound = 0;
int upperBound = data.length - 1;
int mid;

while(true) {
if (lowerBound > upperBound) {
return -1;
}

mid = lowerBound + (upperBound - lowerBound) / 2;
if (data[mid] == key) {
return mid;
}

if (data[mid] < key) {
lowerBound = mid + 1;
} else {
upperBound = mid - 1;
}
}
}

Binary Search requires O(log n) time on a sorted array with n elements.

Advantages of Ordered Arrays

It may be useful in situations where searches are frequent but insertions and deletions are not.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: