/*
*Copyright(c) 2015,煙臺大學計算機學院
*All rights reserved.
*文件名稱:test.cpp
*作者:林莉
*完成日期:2015年12月14日
*版本:v1.0
*
*問題描述:用序列{9,8,7,6,5,4,3,2,1,0}作爲測試數據,運行並本週視頻中所講過的算法對應 程
序,觀察運行結果並深刻領會算法的思路和實現方法:(1)直接插入排序 折半插入排序
*輸入描述:無
*輸出描述:所得結果。
*/
1.直接插入排序
#include <stdio.h>
#define MaxSize 20
typedef int KeyType; //定義關鍵字類型
typedef char InfoType[10];
typedef struct //記錄類型
{
KeyType key; //關鍵字項
InfoType data; //其他數據項,類型爲InfoType
} RecType; //排序的記錄類型定義
void InsertSort(RecType R[],int n) //對R[0..n-1]按遞增有序進行直接插入排序
{
int i,j;
RecType tmp;
for (i=1; i<n; i++)
{
tmp=R[i];
j=i-1; //從右向左在有序區R[0..i-1]中找R[i]的插入位置
while (j>=0 && tmp.key<R[j].key)
{
R[j+1]=R[j]; //將關鍵字大於R[i].key的記錄後移
j--;
}
R[j+1]=tmp; //在j+1處插入R[i]
}
}
int main()
{
int i,n=10;
RecType R[MaxSize];
KeyType a[]= {9,8,7,6,5,4,3,2,1,0};
for (i=0; i<n; i++)
R[i].key=a[i];
printf("排序前:");
for (i=0; i<n; i++)
printf("%d ",R[i].key);
printf("\n");
InsertSort(R,n);
printf("排序後:");
for (i=0; i<n; i++)
printf("%d ",R[i].key);
printf("\n");
return 0;
}
運行結果:
2.顯示直接插入排序過程
#include <stdio.h>
#define MaxSize 20
typedef int KeyType; //定義關鍵字類型
typedef char InfoType[10];
typedef struct //記錄類型
{
KeyType key; //關鍵字項
InfoType data; //其他數據項,類型爲InfoType
} RecType; //排序的記錄類型定義
void InsertSort(RecType R[],int n) //對R[0..n-1]按遞增有序進行直接插入排序
{
int i,j,k;
RecType tmp;
for (i=1; i<n; i++)
{
tmp=R[i];
j=i-1; //從右向左在有序區R[0..i-1]中找R[i]的插入位置
while (j>=0 && tmp.key<R[j].key)
{
R[j+1]=R[j]; //將關鍵字大於R[i].key的記錄後移
j--;
}
R[j+1]=tmp; //在j+1處插入R[i]
printf("i=%d: ",i);
for (k=0; k<n; k++)
printf("%d ",R[k].key);
printf("\n");
}
}
int main()
{
int i,n=10;
RecType R[MaxSize];
KeyType a[]= {9,8,7,6,5,4,3,2,1,0};
for (i=0; i<n; i++)
R[i].key=a[i];
printf("排序前:");
for (i=0; i<n; i++)
printf("%d ",R[i].key);
printf("\n");
InsertSort(R,n);
printf("排序後:");
for (i=0; i<n; i++)
printf("%d ",R[i].key);
printf("\n");
return 0;
}
運行結果:
3.折半插入排序
#include <stdio.h>
#define MaxSize 20
typedef int KeyType; //定義關鍵字類型
typedef char InfoType[10];
typedef struct //記錄類型
{
KeyType key; //關鍵字項
InfoType data; //其他數據項,類型爲InfoType
} RecType; //排序的記錄類型定義
void InsertSort1(RecType R[],int n) //對R[0..n-1]按遞增有序進行直接插入排序
{
int i,j,low,high,mid;
RecType tmp;
for (i=1; i<n; i++)
{
tmp=R[i];
low=0;
high=i-1;
while (low<=high)
{
mid=(low+high)/2;
if (tmp.key<R[mid].key)
high=mid-1;
else
low=mid+1;
}
for (j=i-1; j>=high+1; j--)
R[j+1]=R[j];
R[high+1]=tmp;
}
}
int main()
{
int i,n=10;
RecType R[MaxSize];
KeyType a[]= {9,8,7,6,5,4,3,2,1,0};
for (i=0; i<n; i++)
R[i].key=a[i];
printf("排序前:");
for (i=0; i<n; i++)
printf("%d ",R[i].key);
printf("\n");
InsertSort1(R,n);
printf("排序後:");
for (i=0; i<n; i++)
printf("%d ",R[i].key);
printf("\n");
return 0;
}
運行結果: