#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string>
typedef int ElemType;
typedef struct {
ElemType *elem; //存储元素的起始地址
int TableLen; //元素个数
}SSTable;
void ST_Init(SSTable &ST,int len)
{
ST.TableLen=len;
ST.elem=(ElemType *) malloc(sizeof (ElemType)*ST.TableLen); //申请一块空间,当数组来使用
int i;
srand(time(NULL));//随机数生成,每一次执行代码就会得到随机的10个元素
for (int i = 0; i < ST.TableLen; i++) {
ST.elem[i]=rand()%100; //生成的是0-99之间
}
}
//打印数组中的元素
void ST_print(SSTable ST)
{
for (int i = 0; i < ST.TableLen; i++) {
printf("%3d",ST.elem[i]);
}
printf("\n");
}
void InsertSort(ElemType *A,int n)
{
int i,j,insertVal;
for (i = 1; i < n; i++) //外层控制要插入的数
{
insertVal=A[i]; //保存要插入的数
//内层控制比较,j要大于等于0,同时arr[j]大于insertVal时,arr[j]位置元素往后覆盖
for (j = i - 1; j >= 0 && A[j] > insertVal ; j--)
{
A[j+1]=A[j];
}
A[j+1]=insertVal; //把要插入的元素放到对应位置
}
}
int main() {
SSTable ST;
ST_Init(ST,10); //申请10个元素空间
ST_print(ST); //排序前打印
InsertSort(ST.elem,10);
ST_print(ST); //排序后再次打印
return 0;
}