二分法插入排序算法实验: 编写一个二分法插入排序代码,程序先生成一个包含10个随机整数的序列,生成数范围:从你的座号(比如20)到60,然后将此序列升序排序并输出。
COMMON.H
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<time.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
INSORT.H
#include"common.h"
typedef int KeyType;
typedef int OtherType;
typedef struct
{
KeyType key;
OtherType other_data;
}RecordType;
void CreateListRand(RecordType r[],int len);
void InsSort(RecordType r[],int len);
void BinSort(RecordType r[],int len);
INSORT.C
#include"insort.h"
void CreateListRand(RecordType r[],int len)
{
int i;
printf(“生成的随机列表为:\n”);
srand((int)time(0));
for (i=1;i<=len;i++)
{
int n=rand()%23+37;
r[i].key= n;
printf("%4d",n);
}
printf("\n");
}
void BinSort(RecordType r[],int len)
{
int i,j;
int low,mid, high;
RecordType x;
for(i=2;i<=len;i++)
{
x=r[i];
low=1;
high=i-1;
while(low<=high)
{
mid=(low+high)/2;
if(x.key<r[mid].key)
high=mid-1;
else
low=mid+1;
}
for(j=i-1;j>=low;j--)
r[j+1]=r[j];
r[low]=x;
}
}
MAIN.C
#include"insort.h"
int main()
{
int i, len;
printf(“内部排序算法–折半插入排序\n************************************\n”);
printf(“请输入顺序表长度(不超过20):”);
fflush(stdin);
scanf("%d",&len);
RecordType rt[len+1];
CreateListRand(rt,len);
BinSort(rt,len);
printf("\n排序后的序列为:\n");
for(i=1;i<=len;i++)
printf("%4d",rt[i].key) ;
return 0;
}
冒泡排序改进算法实验: 参照教材中算法9.4,编写一个冒泡排序改进算法,程序先生成一个包含10个随机整数的序列,生成数范围:从你的座号(比如20)到60,然后将此序列降序排序并输出。
COMMON.H
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<time.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
INSORT.H
#include"common.h"
typedef int KeyType;
typedef int OtherType;
typedef struct
{
KeyType key;
OtherType other_data;
}RecordType;
void CreateListRand(RecordType r[],int len);
void InsSort(RecordType r[],int len);
void BinSort(RecordType r[],int len);
void BubbleSort(RecordType r[],int len) ;
INSORT.C
#include"insort.h"
void CreateListRand(RecordType r[],int len)
{
int i;
printf(“生成的随机列表为:\n”);
srand((int)time(0));
for (i=1;i<=len;i++)
{
int n=rand()%23+37;
r[i].key= n;
printf("%4d",n);
}
printf("\n");
}
void BubbleSort(RecordType r[],int len)
{
int i,j;
RecordType x;
for(i=1;i<=len-1;i++)
{
for(j=1;j<=len-i;j++)
{
if(r[j].key <r[j+1].key)
{
x=r[j+1];
r[j+1]=r[j];
r[j]=x;
}
}
}
}
MAIN.C
#include"insort.h"
int main()
{
int i, len;
printf(“内部排序算法–冒泡排序\n************************************\n”);
printf(“请输入顺序表长度(不超过20):”);
fflush(stdin);
scanf("%d",&len);
RecordType rt[len+1];
CreateListRand(rt,len);
BubbleSort(rt,len);
printf("\n排序后的序列为:\n");
for(i=1;i<=len;i++)
printf("%4d",rt[i].key) ;
return 0;
}