示例代码为C语言,输入参数中,需要排序的
数组为array[ ],起始索引为first(数组有序部分最后一个的下标,或者直接标 0),终止索引为last(数组元素的最后一个的下标)。示例代码的函数采用insert-place排序,调用完成后,array[]中从first到last处于升序排列。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
voidinsertion_sort(intarray[],intfirst,intlast)
{
inti,j;
inttemp;
for
(i=first+1;i<=last;i++)
{
temp=array[i];
j=i-1;
//与已排序的数逐一比较,大于temp时,该数移后
while
((j>=first)&&(array[j]>temp))
{
array[j+1]=array[j];
j--;
}
array[j+1]=temp;
}
}
|
这个更好:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
voidinsert_sort(
int
*array,unsignedintn)
{
inti,j;
inttemp;
for
(i=1;i<n;i++)
{
temp=*(array+i);
for
(j=i;j>0&&*(array+j-1)>temp;j--)
{
*(array+j)=*(array+j-1);
}
*(array+j)=temp;
}
}
|