c++实现直接插入排序

#include
#include
using namespace std;

#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define ElemType int

typedef struct{
ElemType *elem;
int length;
int listsize;
}SqList;

//建顺序表
void InitList_Sq(SqList &L)
{
L.elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if (!L.elem) cout << "存储分配失败!" << endl;
L.length = 0;
L.listsize = LIST_INIT_SIZE;
}

//在第i位置插入元素e
void ListInsert_Sq(SqList &L, int i,ElemType e)
{
int *newbase;
if (i<1 || i>L.length + 1) cout << "位置错误!" << endl;
if (L.length >= L.listsize)
{
newbase = (ElemType *)realloc(L.elem, (L.listsize + LISTINCREMENT)*sizeof(ElemType));
if (!newbase) cout << "重新分配地址错误!" << endl;
L.elem = newbase;
L.listsize += LISTINCREMENT;
}
int *p, *q;
q = &(L.elem[i - 1]);
for (p = &(L.elem[L.length - 1]); p >= q; --p) //将第i位置及其以后的元素后移一个位置
*(p + 1) = *p;
*q = e;
++L.length;
}

//直接插入排序
void InsertSort(SqList &L)
{
int T,i,j; //i,j可理解为循环变量,T可理解为哨兵,哨兵可理解为每次要插入的数
for (i = 1; i < L.length; ++i) //最外层循环,判断第i为与第i-1位置大小
if (L.elem[i] < L.elem[i - 1])
{
T = L.elem[i];
for (j = i - 1; T < L.elem[j]; --j) //内循环,决定要插入的位置
{
L.elem[j + 1] = L.elem[j];
}
L.elem[j + 1] = T; //因为临近for循环结束时进行了--j,因此插入位置为j=1
}
}

//打印
void PrintL(SqList &L)
{
int i = 0;
while (i < L.length)
{
cout << L.elem[i]<<" ";
i++;
}
cout << endl;
}

void main()
{
SqList L;

//创建顺序表La并插入数据
InitList_Sq(L);
ListInsert_Sq(L, 1, 56); ListInsert_Sq(L, 2, 25);
ListInsert_Sq(L, 3, 98); ListInsert_Sq(L, 4, 12);
ListInsert_Sq(L, 5, 78); ListInsert_Sq(L, 6, 88);
ListInsert_Sq(L, 7, 39); ListInsert_Sq(L, 8, 95);
ListInsert_Sq(L, 9, 91); ListInsert_Sq(L, 10, 86);
ListInsert_Sq(L, 11, 80); ListInsert_Sq(L, 12, 99);
cout << "La的元素为:";
PrintL(L);

//直接插入排序
InsertSort(L);
cout << "直接插入排序后La的元素为:";
PrintL(L);

//防止运行结果一闪而过
system("pause");
}


你可能感兴趣的:(data,structure)