文章目录
1.基本思想:2.图解3.代码实例
1.基本思想:
设待排序的元素放在数组R[0…n-1]中,排序过程中,R被划分成两个子区间,有序区R[0…i-1]和无序区R[i…n-1],初始时,有序区只有R[0]一个元素,直接插入排序的一趟操作是将当前无序区的开头元素R[i] (1<=i<=n-1)插入到有序区R[0…i-1]中的适当位置,使R[0…i]变为新的有序区
对于第i趟排序,如何将无序区的第一个元素R[i]插入到有序区呢?其过程是先将R[i]暂时放到tmp中,j在有序区中从后向前找(初值为i),凡是关键字大于tmp.key的记录均向后移一个位置。若找到某个R[j],其关键字小于或等于tmp.key,则将tmp 放到他们的后面,即R[j] = temp
2.图解
图片来自博主:https://blog.csdn.net/qq_37623612/article/details/80312121
3.代码实例
#include<stdio.h>
typedef struct {
int key
;
}RecType
;
void InsertSort(RecType R
[], int n
) {
printf("\n");
int i
, j
;
RecType temp
;
for (i
= 1; i
< n
; i
++) {
j
= i
;
temp
= R
[i
];
while (j
> 0 && temp
.key
< R
[j
- 1].key
) {
R
[j
] = R
[j
- 1];
j
--;
}
R
[j
] = temp
;
}
for(int k
= 0;k
<n
;k
++) {
printf("%d \n",R
[k
].key
);
}
}
int main() {
RecType R
[3] = {
{5},
{4},
{7}
};
int n
= 3;
for(int k
= 0;k
<n
;k
++) {
printf("%d \n",R
[k
].key
);
}
printf("----------------------------");
InsertSort(R
,n
);
}
运行结果如下