基于C语言的直接插入排序算法

#include<stdio.h>

/*直接插入排序

插入排序的基本思想是:每次将一个待排序的元素,按
其关键字大小插入到已经排好序的子表中的适当位置,
直到全部元素插入完成为止*/

typedef int KeyType;
typedef struct
{
KeyType key;
char a;
}RecType;
void InsertSort(RecType R[],int n){
int i,j;
RecType temp;
for(i=1;i<n;i++){
temp=R[i];
j=i-1;
while(j>=0&&temp.key<R[j].key){
R[j+1]=R[j];
j--;
}
R[j+1]=temp;
}
}
void main(){
int i;
RecType R[5]={{9,'s'},{2,'f'},{4,'d'},{5,'a'},{1,'g'}};
InsertSort(R,5);
for(i=0;i<5;i++){
  printf("%d\t",R[i].key);
  printf("%c\n",R[i].a);
}
   
}

猜你喜欢

转载自blog.csdn.net/weixin_40745306/article/details/80671323