//数组的数据结构
typedef struct Array//
{
int *Base; //数组首指针
int Cnt; //数组个数
int Len; //数组大小
} Array;
//初始化一个数组
void Init_arr(Array *pArr,int Len)
{
pArr->Base=(int*)malloc(Len*sizeof(int));
if(NULL==pArr->Base)//分配失败
{
printf("内存分配失败");
exit(-1);//抛出异常
}
else
{
pArr->Len=Len;
pArr->Cnt=0;
}
}
//向pArr线表的pos位置上插入一个整数Val
int Insert_arr(Array *pArr,int pos,int Val)
{
if(pos>pArr->Cnt||pArr->Cnt==pArr->Len)//位置大于长度或列表满 抛出异常
{
printf("长度过大或线表已满");
exit(-1);//
}
else
{
int i;
for(i=pArr->Cnt;i>pos;i--)
pArr->Base[i]=pArr->Base[i-1];
pArr->Base[pos]=Val;
pArr->Cnt++;
}
return 0;
}
//线表pArr删除第pos位置的元素
int Delete_arr(Array *pArr,int pos)
{
if(pArr->Cnt<=0)
{
printf("表空");
exit(-1);
}
if(pos>pArr->Cnt||pos<0)
{
printf("位置非法");
exit(-2);
}
else
{
int i,n;
n=pArr->Base[pos];
for(i=pos;i<pArr->Cnt-1;i++)
pArr->Base[i]=pArr->Base[i+1];
pArr->Cnt--;
printf("DELETE=%d\n",n);
return n;
}
}
int Count(Array *pArr)//返回线表元素个数
{
printf("Length=%d",pArr->Cnt);
return pArr->Cnt;
}
int GetElment_arr(Array *pArr,int pos)//取第pos个元素
{
printf("Array[%d]=%d",pos,pArr->Base[pos])
return pArr->Base[pos]
}
void SelectSort_arr(Array *pArr)//直接排序
{
int i,j,temp;
for(i=0;i<pArr->Cnt-1;i++)
for(j=i+1;j<pArr->Cnt;j++)
{
if (pArr->Base[i]>pArr->Base[j])
{
temp=pArr->Base[i];
pArr->Base[i]=pArr->Base[j];
pArr->Base[j]=temp;
}
}
Printf_arr(pArr);
}
void BubbleSrot_arr(Array *pArr)//冒泡
{
int i,j,temp;
for(i=0;i<pArr->Cnt-1;i++)
for(j=0;j<pArr->Cnt-i-1;j++)
{
if(pArr->Base[j+1]>pArr->Base[j])
{
temp=pArr->Base[j+1];
pArr->Base[j+1]=pArr->Base[j];
pArr->Base[j]=temp;
}
}
Printf_arr(pArr);
}
void Printf_arr(Array *pArr)//打印线表
{
printf("cnt=%d\tlen=%d\n",pArr->Cnt,pArr->Len);
int i;
for(i=0;i<pArr->Cnt;i++)
printf("array[%d]=%d\t",i,pArr->Base[i]);
printf("\n");
}
int main()
{
Array A;
Init_arr(&A,20);
Insert_arr(&A,0,4);
Insert_arr(&A,0,5);
Insert_arr(&A,0,3);
Insert_arr(&A,1,7);
Insert_arr(&A,3,9);
Insert_arr(&A,4,11);
Insert_arr(&A,6,8);
Insert_arr(&A,1,2);
Printf_arr(&A);
//SelectSort_arr(&A);
BubbleSrot_arr(&A);
return 0;
}