标签:
//插入排序伪代码
for i <-- 1 to n-1
for j <-- i-1 to 0
if a[i] > a[j] break
if j!=i-1
temp <-- a[i]
for k <-- i to j+2
a[k] <-- a[k-1]
a[j+1] <-- temp
插入排序流程图
插入排序代码实现
/**
* to sort an array a[],the length of a shouldn‘t be negative
* and after the sort,the content of array a has changed.
*
* @parm a[] the array to be sorted
* @parm len the length of the array a
*
* @return there is no return,only to sort the array
*/
void insertSort(int a[], int len){
int temp;//used to save the value of a[i]
/**
* to find the place of the element which index is i
* we think that the first element a[0] is at the right place
* next we find the place for elements which index is from 1 to n-1
*/
for(int i = 1; i < n; i++){
/**
* we would find the place for the element which index is i if
* the value of a[i] is bigger the a[j],so we break to do next thing
*/
for(int j = i-1; j >= 0; j--){
if(a[i] > a[j])
break;
}
/**
* if the value j is not equals to i-1,we would know that the place of a[i]
* is not i-1,so we have to move all the element which index is bigger than j
* and next we put element a[i] to the place which index is j+1
*/
if(j!=i-1){
temp = a[i];
for(int k = i; k > j+1; k--){
a[k] = a[k-1];
}
a[j+1] = temp;
}
}
}
标签:
原文地址:http://www.cnblogs.com/chengsong/p/5335710.html