插入的下标/插入的数均使用随机数rand;
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
void initArr();//
void showArr();//
bool addArr();//
bool insertArr();//
bool deleteArr();//
int getArr();//
bool isEmpty();//
bool isFull();//
void sortArr();//
struct Arr //定义结构体
{
int* pBase;
int lengh;
int cnt;
};
void initArr(struct Arr* arr1, int len) //初始化数组
{
arr1->pBase = (int*)malloc(sizeof(int) * len);
arr1->cnt = 0;
arr1->lengh = len;
}
bool isEmpty(struct Arr* arr) //判断数组是否为空
{
if (arr->cnt == 0) {
return true;
}
return false;
}
bool isFull(struct Arr* arr) //判断数组是否已满
{
if (arr->cnt == arr->lengh)
return true;
else
return false;
}
bool addArr(struct Arr* arr, int value) //数组末尾添加元素
{
if (isFull(arr))
{
cout << "数组已满!" << endl;
return false;
}
else
{
arr->pBase[arr->cnt] = value;
arr->cnt++;
}
return true;
}
bool insertArr(struct Arr* arr, int pos, int value) //插入元素到对应下标
{
if (isFull(arr))
{
cout << "数组已满" << endl;
return false;
}
else {
for (int i = arr->cnt - 1; i >= pos ; --i)
{
arr->pBase[i + 1] = arr->pBase[i];
}
arr->pBase[pos] = value;
arr->cnt++;
}
return true;
}
bool deleteArr(struct Arr* arr, int pos) //删除对应下标的元素
{
if (isEmpty(arr))
{
cout << "数组为空!" << endl;
}
else
{
for (int i = pos; i <= arr->cnt - 1; i++)
{
arr->pBase[i] = arr->pBase[i + 1];
}
arr->cnt--;
}
return true;
}
int getArr(struct Arr *arr,int pos)
{
return arr->pBase[pos];
}
void showArr(struct Arr* arr) //获取数组列表
{
if (isEmpty(arr))
{
cout << "数组为空!" << endl;
}
else {
for (int i = 0; i < arr->cnt; i++)
{
cout << (arr->pBase[i]) << endl;
}
}
}
void sortArr(struct Arr *arr) //数组排序(冒泡排序法)
{
for (int i = 0; i < arr->cnt-1; i++)
{
for (int j = 0; j < arr->cnt - i - 1; j++)
{
if (arr->pBase[j] > arr->pBase[j + 1])
{
int temp = arr->pBase[j];
arr->pBase[j] = arr->pBase[j + 1];
arr->pBase[j + 1] = temp;
}
}
}
}
int main(int argc, char const* argv[])
{
struct Arr arr1;
initArr(&arr1, 6);
cout << "数组初始化完成!" << endl;
cout << "---------------------" << endl;
showArr(&arr1);
cout << "数组为空,开始插入元素......" << endl;
addArr(&arr1, rand() % 100);
addArr(&arr1, rand() % 100);
addArr(&arr1, rand() % 100);
addArr(&arr1, rand() % 100);
addArr(&arr1, rand() % 100);
cout << "插入元素完成!" << endl;
cout << "---------------------" << endl;
cout << "插入的元素为:" << endl;
showArr(&arr1);
cout << "---------------------" << endl;
cout << "测试插入算法:" << endl;
insertArr(&arr1, rand() % arr1.lengh, rand()%100);
showArr(&arr1);
cout << "测试插入算法结束" << endl;
cout << "---------------------" << endl;
cout << "测试删除算法:" << endl;
deleteArr(&arr1, rand() % arr1.lengh);
showArr(&arr1);
cout << "测试删除算法结束" << endl;
cout << "---------------------" << endl;
cout << "测试获取元素算法:" << endl;
cout<<getArr(&arr1, rand() % arr1.lengh)<<endl;
cout << "测试插入算法结束" << endl;
cout << "---------------------" << endl;
cout << "测试获取元素排序算法:" << endl;
sortArr(&arr1);
showArr(&arr1);
cout << "测试元素排序算法结束" << endl;
cout << "---------------------" << endl;
return 0;
}