下面是我些的代码和运行结果:
// 由计算机随机产生10个0~100之间的整数存入数组a中,并将这些数从小到大排序,然后输入一个整数x,在数组a中查找x,若找到则输出相应的下标,否则输出“未找到”。
#include <stdlib.h>
#include <stdio.h>
#define MAX 100
#define N 10
int a[N];
int count = N;
void populate()
{
for (int i = 0; i < count; ++i)
{
a[i] = rand() % (MAX + 1);
}
}
// 具体要求: (1)用选择排序法或冒泡排序法进行排序。
void bubble_sort()
{
for (int i = 0; i < count - 1; ++i)
for (int j = i + 1; j < count; ++j)
if (a[i] > a[j])
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
// (2)用顺序查找法或折半查找法进行查找。
int find(int x)
{
for (int i = 0; i < count; ++i)
if (a[i] == x)
return i;
return -1;
}
// (3)如果要删除查找到的元素值,如何修改程序?
int remove(int x)
{
for (int i = 0; i < count; ++i)
if (a[i] == x)
{
for (int j = i + 1; j < count; ++j)
a[j - 1] = a[j];
--count;
return i;
}
return -1;
}
// 主函数一次调用前面的函数
int main()
{
int x;
int index;
populate();
bubble_sort();
printf("Here are the %d numbers:\n", count);
for (int i = 0; i < count; ++i)
printf("%d ", a[i]);
printf("\n");
printf("Please enter a number (0 .. 100) to look for and press ENTER: ");
scanf("%d", &x);
index = find(x);
if (index != -1)
printf("Found it! Its index (0-based) is %d\n", index);
else
printf("Not found.\n");
printf("Please enter a number (0 .. 100) to look for and press ENTER: ");
scanf("%d", &x);
index = find(x);
if (index != -1)
printf("Found it! Its index (0-based) is %d\n", index);
else
printf("Not found.\n");
printf("Please enter a number (0 .. 100) to delete and press ENTER: ");
scanf("%d", &x);
index = remove(x);
if (index != -1)
printf("Deleted it! Its index (0-based) was %d\n", index);
else
printf("Not found.\n");
printf("Here are the %d numbers:\n", count);
for (int i = 0; i < count; ++i)
printf("%d ", a[i]);
printf("\n");
}
// Output:
Here are the 10 numbers:
8 12 30 32 32 44 52 54 56 94
Please enter a number (0 .. 100) to look for and press ENTER: 44
Found it! Its index (0-based) is 5
Please enter a number (0 .. 100) to look for and press ENTER: 40
Not found.
Please enter a number (0 .. 100) to delete and press ENTER: 12
Deleted it! Its index (0-based) was 1
Here are the 9 numbers:
8 30 32 32 44 52 54 56 94
附注:求赞助积分和C币。加入CSDN将近20年了。最近几年忙小孩没登录。刚才搜索到一本电子书想下载,需要20积分/C币。赞助多少都可以。多谢。