?? 直接插入排序.cpp
字號:
//* * * * * * * * * * * * * * * * * * * * * * * *
//*CHAPTER :7 (7_1) *
//*PROGRAM :直接插入排序 *
//*CONTENT :直接插入排序 *
//* * * * * * * * * * * * * * * * * * * * * * * *
#include <dos.h>
#include <conio.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20 //排序表的最大容量
typedef struct //定義排序表的結(jié)構(gòu)
{int elemword[MAXSIZE]; //數(shù)據(jù)元素關(guān)鍵字
int count; //表中當(dāng)前元素的個(gè)數(shù)
}SqList;
void InitialSqList(SqList&); //初始化排序表
void InsertSort(SqList&); //直接插入排序
void PrintSqList(SqList); //顯示表中的所有元素
void main()
{SqList L; //聲明表L
char j='y';
textbackground(3); //設(shè)定屏幕顏色
textcolor(15);
clrscr();
//-------------------------程序說明-------------------------------
printf("本程序?qū)⒀菔局苯硬迦肱判虻牟僮鳌n");
//----------------------------------------------------------------
while(j!='n'&&j!='N')
{InitialSqList(L);
InsertSort(L);
PrintSqList(L);
printf("繼續(xù)進(jìn)行下一次排序嗎?(Y/N)");
scanf(" %c",&j);
}
printf("程序運(yùn)行結(jié)束!\n按任意鍵關(guān)閉窗口!\n");
getchar();getchar();
}
void InitialSqList(SqList &L)
{//表初始化
int i;
printf("請輸入待排序的記錄的個(gè)數(shù):");
scanf("%d",&L.count);
printf("請輸入待排序的記錄的關(guān)鍵字(整型數(shù)):\n");
for(i=1;i<=L.count;i++)
scanf("%d",&L.elemword[i]);
}
void InsertSort(SqList &L)
{int i,j;
for(i=2;i<=L.count;i++)
if(L.elemword[i]<L.elemword[i-1]) //"<",需將L.elemword[i]插入有序子表
{ L.elemword[0]=L.elemword[i]; //復(fù)制為哨兵
for(j=i-1;L.elemword[0]<L.elemword[j];--j)
L.elemword[j+1]=L.elemword[j]; //記錄后移
L.elemword[j+1]=L.elemword[0]; //插入到正確的位置
}
}
void PrintSqList(SqList L)
{//顯示表所有元素
int i;
printf("已排好序的序列如下:\n");
for(i=1;i<=L.count;i++)
printf("%4d",L.elemword[i]);
printf("\n");
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -