第一小题
#include<stdio.h>
#include<stdlib.h>
#define N 10
//第二题,删除元素
int del(int array[], int len, int num);
int main()
{
int a[N] = { 1, 7,7, 8, 17, 23, 24, 59, 62, 101 };
int i, n = 10;
int m = 7;
int del_count;
del_count = del(a, n, m); //在长度为n的a数组中删除数字m
printf("%d\n", del_count);
for (i = 0; i<del_count; ++i)
printf("%d ", a[i]);
printf("\n");
return 0;
}
int del(int array[], int len, int num)
{
int i,j,temp;
int count=0;
for (i = 0; i < len; i++)
{
if (array[i] == num)
{
for (j = i; j < len - count-1; j++)
array[j] = array[j + 1];
count++;
i--;//删除后i+1位置的元素变为i
}
}
return len-count;
}
补充一下老师的做法,比我的更好,赋值运算(也就是“搬运”的动作)的次数更少,相对来讲消耗时间也较少
#include<stdio.h>
int del(int a[],int n, int x);
int main( )
{
int a[20]= {86,76,62,58,77,85,92,80,96,88,77,67,80,68,78,87,64,59,61,76};
int i, n;
n = del(a, 20, 77);
printf("剩余 %d 个:\n", n);
for(i=0; i<n; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
int del(int a[],int n, int x) //删除长度为n的a数组中值为x的元素
{
int p=0, q=0; //用p和q两个变量
while (q<n) //由q控制,扫描所有的元素
{
if(a[q]!=x) //只有当元素值不等于x才往p标识的位置上“搬”
{
a[p]=a[q];
p++;
}
q++;
} //最后的效果,等于x的元素都没有“搬”过来,它们被“覆盖”了,也即被删除了
return p; //p代表的,就是删除后的元素个数
}
第二小题#include<stdio.h>
#include<stdlib.h>
//第二题,删除元素,排序的主要意义在于当数据量较大时可以通过二分法快速定位到元素的位置,确定有哪些元素需要进行替换,避免了遍历了全部元素的效率损耗
int del(int array[], int len, int num);
void sort(int array[],int len);
int main()
{
int a[20] = { 86, 76, 62, 58, 77, 85, 92, 80, 96, 88, 77, 77, 67, 80, 68, 78, 87, 64, 59, 61 };
int i;
int del_count;
sort(a, 20);
for (i = 0; i < 20; i++)
printf("%d ", a[i]);
printf("\n");
del_count = del(a, 20, 77); //在长度为n的a数组中删除数字m
printf("%d\n", del_count);
for (i = 0; i<del_count; ++i)
printf("%d ", a[i]);
printf("\n");
return 0;
}
void sort(int array[], int len)
{
int i,j;
int min,temp;
for (i = 0; i < len - 1; i++)
for (j = i; j < len; j++)
if (array[j] < array[i])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
int del(int array[], int len, int num)
{
int i,j;
int count=0;
for (i = 0; i < len; i++)
{
if (array[i] == num)
{
for (j = i; j < len - count - 1; j++)
array[j] = array[j + 1];
count++;
i--;//删除后i+1位置的元素变为i
}
}
return len-count;
}