#include
// 输入
void input(int a[], int len)
{
int i = 0;
while (i < len)
{
scanf("%d", &a[i++]);
}
}
// 输出
void output(int a[], int len)
{
printf("[ ");
int i = 0;
while (i < len) printf("%3d ", a[i++]);
printf("]\n");
}
// 排序
void reorder(int a[], int len)
{
int i, j, index, max;
for (i = len - 1; i >= 0; i--)
{
index = 0;
max = 0;
for (j = 0; j <= i; j++)
{
if (a[j] > max)
{
max = a[j];
index = j;
}
}
a[index] = a[i];
a[i] = max;
}
}
// 查找
int search(int a[], int begin, int end, int target)
{
int left = begin;
int right = end;
int mid = (left + right) / 2;
if (left >= right)
return -1;
if (a[mid] == target)
return mid;
else if (a[mid] < target)
return search(a, mid, right, target);
else
return search(a, left, mid, target);
}
// 插入
void insert(int a[], int len, int target)
{
int i = 0;
int index = -1;
if (target <= a[0]) index = 0;
else if (target >= a[len - 1]) index = len;
else
{
for (i = 0; i < len; i++)
{
if (a[i] < target && a[i + 1] >= target)
{
index = i + 1;
break;
}
}
}
for (i = len; i > index; i--)
{
a[i] = a[i - 1];
}
a[index] = target;
}
// 删除
void delete(int a[], int len, int target)
{
int index = search(a, 0, len, target);
if (index != -1)
{
int i = 0;
for (i = index; i < len; i++)
{
a[i] = a[i + 1];
}
}
}
int main()
{
int a[30] = {0};
int count = 20;
int index = -1;
int x = -1;
printf("Please input %d integers:", count);
input(a, count);
printf("The numbers you input are:\n");
output(a, count);
printf("Please input the x you want to insert: x = ");
scanf("%d", &x);
printf("Firstly, we reorder these numbers...\n");
reorder(a, 10);
printf("Now we get an array like this:\n");
output(a, 10);
printf("Search %d in the array...\n", x);
index = search(a, 0, count, x);
if (index == -1)
{
printf("We CAN NOT find %d in the array, so we insert it.\n", x);
insert(a, count, x);
count++;
}
else
{
printf("Wow, we found it, so we delete it...\n");
delete(a, count, x);
count--;
}
printf("Now let us check up the content in the array:\n");
output(a, count);
printf("\nThanks for your using!\n");
return 0;
}