Sorting algorithm (a) and insertion sort Java implementation

Code:

public void insertionSort(List<T> list, Comparator<T> comparator) {
for (int i=1; i<list.size(); i++) {
T elt_i = list.get(i);
int j = i;

while (j>0) {
T elt_j = list.get(j-1);
if (comparator.compare(elt_i,elt_j)>=0) {
break;
}
list.set(j,elt_j);
j--;
}
list.set(j,elt_i);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
测试:

List<Integer> list = new ArrayList<Integer>(Arrays.asList(3, 5, 1, 4, 2));

Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer elt1, Integer elt2) {
return elt1.compareTo(elt2);
}
};

ListSorter <Integer> = new new ListSorter Sorter <Integer> ();
sorter.insertionSort (List, Comparator);
System.out.println (List);
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
. 11
12 is
InsertionSort two nested cycle, so you might guess, its running time is quadratic. In this case, the general is right, but before you make that conclusion, you have to check each cycle of operation and the number n, is proportional to the size of the array.

Outer loop iterations from 1 to list.size (), and therefore n is linear to the size of the list. The inner loop iteration from i to 0, n is also in the linear. Therefore, the total number of two cycle operation is quadratic.

If you are unsure, here is the proof:

In the first cycle, i = 1, the inner loop runs at most once. Second, i = 2, the maximum of two cycle operation. Last, i = n - 1, the operating cycle of up to n times.

Thus, the total number of cycles run is the sequence 1, 2, ..., n - 1 and that n (n - 1) / 2. The main item of the expression (highest index) as n ^ 2.

In the worst case, insertion sort is quadratic. however:

If these elements has been ordered, or nearly so, insertion sort is linear. Specifically, if the distance of each element does not exceed its ordered position of k elements, then the inner loop does not run more than k, and the total running time is O (kn).
Due to simple, low cost; that is, although the running time is an ^ 2, the main item of the coefficients a, it may be small.
So if we know almost orderly array, or is not great, insertion sort might be a good choice.
---------------------

Guess you like

Origin www.cnblogs.com/ly570/p/11106211.html