排序算法——插入排序(Insertion Sort)
伪代码(Pseudocode):
function INSERTIONSORT(A[0..n-1])
for i ⟵ 1 to n-1 do
v ⟵ A[i]
j ⟵ i-1
while j ≥ 0 and v < A[j] do
A[j+1] ⟵ A[j]
j ⟵ j-1
A[j+1] ⟵ v
基本属性(Property):
Input: an array A[0..n-1] of n orderable elements
Output: an array A[0..n-1] sorted in nondeacending order
The size of input: n
Basic operation: key comparison “v < A[j]”
In-place: YES. only requires a constant amount O(1) of additional memory space.
Stable: YES. does not change the relative order of elements with equal keys.
时间复杂度(Time Complexity):
The for loop is traversed n-1 times. In the ith round, the comparison “v < A[j]” is performed i times in the worst case(array A[0..n-1] is sorted in descending order).
Hence, the worst-case running time is
In the best case, which is array A[0..n-1] is already a sorted array.
In the average case.
适用情形(Suitable Situation):
1. Linear time for almost-sorted array.
2. Small array (a couple of hundreds elements).
3. Some clever sorting algorithms perform amost-sorting and then let insertion sort take over.
Java Code:
public class Sort{
//Insertion sort method
public static int[] insertionSort(int[] A){
int i,j,tmp;
for(i=1;i<A.length;i++){
tmp=A[i];
j=i-1;
while(j>=0 && A[j]>tmp){
A[j+1]=A[j];
j--;
}
A[j+1]=tmp;
}
return A;
}
//Test
public static void main(String[] args){
int[] A={1,20,14,78,34,76,11,9,100,52};
int[] sortedA=Sort.insertionSort(A);
for(int i=0;i<sortedA.length;i++)
System.out.print(sortedA[i]+" ");
}
}
运行结果(Result):
1 9 11 14 20 34 52 76 78 100
写在最后的话(PS):
This is my first time to write blog. I hope it will be helpful. If there are some issues, please comment. I’m very welcome to talk about it.