This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
We can insert the new element in the correct place with fewer assignment operations - only 4!
10 30 60 20
0 1 2 3
temp1
10 30 60 20
0 1 2 32
temp 10 30 60 20
0 1 2 33
temp
10 30 60 20
0 1 2 34
temp
In general if an element is moved (p) places it only takes (p + 2) assignment operations, not (3*p) assignment operations as required by (p) exchanges.
public void insertElementAt(Object object, int index) {//pre: 0 <= index <= size()//post: inserts the given object at the given index,// moving elements from index to size()-1 to the right
int i;
this.ensureCapacity(this.elementCount + 1);for (i = this.elementCount; i > index; i--)
Differences from Differences from Element InsertionElement Insertion
In Vector element insertion:– We have a reference to the new element.
– We know the index location for the new element.
In the Insertion sort:– We don’t have a reference to the new element, only an
index in the array where the new element is currently located.
– We don’t know the index location for the new element. We need to find the index by comparing the new element with the elements in the collection from left to right.
public static void moveElementAt(Comparable anArray[], int last) {
// pre: 0 <= last < anArray.length and anArray in// ascending order from 0 to last-1.// post: anArray in ascending order from 0 to last // int move; //A reference to the element being moved
In the best case there is 1 comparison per call and it fails. This means there are 0 successful comparisons, so there are 0+2 = 2 assignments per call.
In the best case there is a total number of assignments: 2 *(n-1) = O(n). When will this happen?
We have already seen that the average number of comparisons when inserting an element into a list of size k is: (k+1)/2(k+1)/2.
On average, half of the time, the last comparison succeeds and half of the time it fails so the average number of successful comparisons is:(k+1)/2 - (1/2) = (k/2)(k+1)/2 - (1/2) = (k/2)
Therefore, the average number of total assignmentsaverage number of total assignments is:1/2 + 2/2 + … + (n-1)/2 = [1 + 2 + … + (n-1)]*(1/2) [ (n-1)*n/2]*(1/2) = (n-1)*n/4 = O(n(n-1)*n/4 = O(n22))
Time Complexity of Time Complexity of Insertion SortInsertion Sort
Best case O(n)Best case O(n) for comparisons and assignments.
Worst case O(nWorst case O(n22)) for comparisons and assignments.
Average case O(nAverage case O(n22)) for comparisons and assignments.
Note: this means that for nearly sorted nearly sorted collectionscollections, insertion sort is better than selection sort even though in average and worst cases, they are the same: O(nO(n22).).