关于连续存储数组算法的实现
包含算法2.3,算法2.4,算法2.5的思想
代码区
#include <iostream>
#include <malloc.h>
using namespace std;
struct Arr
{
int * a;
int len;
int loclen;
};
void Init_arr(Arr *arr,int lenth);
void get(Arr* arr,int input);
bool isfull(Arr* arr);
bool append_arr(Arr* arr,int val);
void show(Arr* arr);
bool insert_arr(Arr* arr,int pos, int val);
bool delete_arr(Arr* arr,int pos);
void sort_arr(Arr* arr);
void inversion_arr(Arr* arr);
int main()
{
Arr arr;int input;
Init_arr(&arr,6); //初始化arr数组,6表示数组长度
get(&arr,2);
get(&arr,1);
get(&arr,3);
if(append_arr(&arr,4)) //在数组后插入数值
cout<<"追加成功"<<endl;
if(insert_arr(&arr,3,5))
cout<<"插入成功"<<endl;
else
cout<<"插入失败"<<endl;
show(&arr);
if(delete_arr(&arr,3))
cout<<"删除成功"<<endl;
else
cout<<"删除失败"<<endl;
show(&arr);
if(insert_arr(&arr,3,6))
cout<<"插入成功"<<endl;
else
cout<<"插入失败"<<endl;
show(&arr);
if(insert_arr(&arr,1,5))
cout<<"插入成功"<<endl;
else
cout<<"插入失败"<<endl;
cout<<"接下来进行排序:"<<endl;
show(&arr);
sort_arr(&arr);
cout<<"排序完的序列为"<<endl;
show(&arr);
cout<<"接下来反向排序:"<<endl;
inversion_arr(& arr);
cout<<"排序完的序列为"<<endl;
show(&arr);
return 0;
}
void Init_arr(Arr *arr,int lenth)
{
if(lenth<=0)
{
cout<<"数组长度输入有误"<<endl;
return;
}
arr->a=(int *)malloc(sizeof (int)*lenth);
arr->len=6; //假设数组的长度为6
arr->loclen=0;
}
void get(Arr* arr,int input)
{
if(!isfull(arr))
{
arr->a[arr->loclen]=input;
arr->loclen++;
}
else
cout<<"数据输入失败!!!"<<endl;
}
bool isfull(Arr* arr)
{
if(arr->loclen==arr->len)
{
cout<<"数组已满,无法输入!!!"<<endl;
return true;
}
else
return false;
}
bool append_arr(Arr* arr,int val)
{
if(!isfull(arr))
{
arr->a[arr->loclen]=val;
arr->loclen++;
return true;
}
return false;
}
void show(Arr* arr)
{
for(int i=0;i<arr->loclen;i++)
{
cout<<arr->a[i]<<" "<<endl;
}
}
bool insert_arr(Arr* arr,int pos, int val)
{
pos--;
if(pos<0||pos>arr->loclen)
return false;
if(!isfull(arr))
{
for(int i=arr->loclen-1;i>=pos;i--)
{
arr->a[i+1]=arr->a[i];
}
arr->a[pos]=val;
arr->loclen++;
}
}
bool delete_arr(Arr* arr,int pos)
{
pos--;
if(pos<0||pos>=arr->loclen)
return false;
cout<<"你要删除的数字是"<<arr->a[pos]<<endl;
for(int i=pos;i<arr->loclen-1;i++)
{
arr->a[i]=arr->a[i+1];
}
arr->loclen--;
return true;
}
void sort_arr(Arr* arr)
{
int i=0,j;
for(i;i<arr->loclen-1;i++)
{
for(j=i+1;j<arr->loclen;j++)
{
if(arr->a[i]<arr->a[j])
{
int temp=arr->a[i];
arr->a[i]=arr->a[j];
arr->a[j]=temp;
}
}
}
}
void inversion_arr(Arr* arr)
{
int i=0,j=arr->loclen-1;
while(i<j)
{
int temp=arr->a[i];
arr->a[i]=arr->a[j];
arr->a[j]=temp;
i++,j--;
}
}