問題:
Description
算法設計:實現直接插入排序。void InsertSort(RecType R[],int n)爲對R[0..n-1]按遞增有序進行直接插入排序。主函數已經給出。
注意:只提交void InsertSort(RecType R[],int n) //對R[0..n-1]部分。
#include <stdio.h>
#define MAXE 20 //線性表中最多元素個數
typedef int KeyType;
typedef char InfoType[10];
typedef struct //記錄類型
{
KeyType key; //關鍵字項
InfoType data; //其他數據項,類型爲InfoType
} RecType;
int main()
{
int i,k,n;
KeyType a[100];
RecType R[MAXE];
scanf("%d",&n);
for (i=0; i<n; i++)
scanf("%d",&a[i]);
for (i=0; i<n; i++)
R[i].key=a[i];
printf("初始關鍵字: "); //輸出初始關鍵字序列
for (k=0; k<n; k++)
printf("%3d",R[k].key);
printf("\n");
InsertSort(R,n);
printf("最後結果: "); //輸出初始關鍵字序列
for (k=0; k<n; k++)
printf("%3d",R[k].key);
printf("\n");
return 0;
}
Input
輸入帶排序元素的個數
輸入待排序的整數
Output
輸出初識數據
輸出排序後的數據
Sample Input
10 9 2 7 5 6 4 8 3 1 0
Sample Output
初始關鍵字: 9 2 7 5 6 4 8 3 1 0最後結果: 0 1 2 3 4 5 6 7 8 9
HINT
請使用C++編譯並提交
Source
直接插入排序思路:先將第一個元素作爲有序組,後面的元素作無序組,然後不斷從無序組中拿出元素,插入到有序組中,並保證有序組中是有序的,最後得到有序序列。圖示(來自百度百科):
此題代碼:
#include <stdio.h>
#define MAXE 20 //線性表中最多元素個數
typedef int KeyType;
typedef char InfoType[10];
typedef struct //記錄類型
{
KeyType key; //關鍵字項
InfoType data; //其他數據項,類型爲InfoType
} RecType;
void InsertSort(RecType R[],int n);
void InsertSort(RecType R[],int n)
{
int t,i,j;
for(i=1; i<n; i++)
{
if(R[i].key<R[i-1].key)
{
t=R[i].key;
for(j=i-1; j>=0 && R[j].key>t; j--)
{
R[j+1].key=R[j].key;
}
R[j+1].key=t;
}
}
}
int main()
{
int i,k,n;
KeyType a[100];
RecType R[MAXE];
scanf("%d",&n);
for (i=0; i<n; i++)
scanf("%d",&a[i]);
for (i=0; i<n; i++)
R[i].key=a[i];
printf("初始關鍵字: "); //輸出初始關鍵字序列
for (k=0; k<n; k++)
printf("%3d",R[k].key);
printf("\n");
InsertSort(R,n);
printf("最後結果: "); //輸出初始關鍵字序列
for (k=0; k<n; k++)
printf("%3d",R[k].key);
printf("\n");
return 0;
}
運行:
興致勃勃的去提交,結果被告知編譯錯誤。。。。。。
仔細一看才發現。。。。
我能怎麼辦......我也很無奈啊.......
小結:學習了直接插入排序。