C语言输入任意长度数组后,再在该数组中查找特定的值,并且可查找多个相同的值
例:在a[20] = { 99,42,57,74,46,85,32,78,40,33,74,88,65,27,38,69,51,32,59,24 }中查找32,需要查找到两个32的位置
#include
#include
void shellSort(int* a, int len); // 函数声明
int binary_search(int a[], int x, int len);
int main(void)
{
int i, len, * a, * b;
printf("请输入数组长度:");
scanf_s("%d", &len);
a = (int*)malloc(len * sizeof(int)); // 动态定义数组
b = (int*)malloc(len * sizeof(int)); // 动态定义数组
printf("请输入数组的每个元素:\n");
for (i = 0; i < len; i++) // 数组值的输入
scanf_s("%d", &a[i]);
for (i = 0; i < len; i++)
b[i] = a[i];
//int a[20] = { 99,42,57,74,46,85,32,78,40,33,74,88,65,27,38,69,51,32,59,24 };
//int b[20] = { 99,42,57,74,46,85,32,78,40,33,74,88,65,27,38,69,51,32,59,24 };
shellSort(a, len); // 调用希尔排序函数
printf("希尔升序排列后结果为:\n");
for (i = 0; i < len; i++) // 排序后的结果的输出
printf("%d\t", a[i]);
printf("\n");
int ret = 0, * c, n = 0, x;
printf("请输入要查找的数组元素:");
scanf_s("%d", &x);
ret = binary_search(a, x, len);
c = (int*)malloc(ret * sizeof(int)); // 动态定义数组
if (ret != -1)
{
for (i = 0; i < len; i++)
if (b[i] == x)
{
c[n] = i;
n++;
}
printf("数组内元素等于%d的下标为:\n",x);
for (i = 0; i < ret; i++) // 排序后的结果的输出
printf("%d\t", c[i]);
}
else
printf("查询无果");
return 0;
}
//希尔排序
void shellSort(int* a, int len)
{
int i, j, k, tmp, gap; // gap 为步长
for (gap = len / 2; gap > 0; gap /= 2) // 步长初始化为数组长度的一半,每次遍历后步长减半,
for (i = 0; i < gap; ++i) // 变量 i 为每次分组的第一个元素下标
for (j = i + gap; j < len; j += gap) //对步长为gap的元素进行直插排序,当gap为1时,就是直插排序
{
tmp = a[j]; // 备份a[j]的值
k = j - gap; // j初始化为i的前一个元素(与i相差gap长度)
while (k >= 0 && a[k] > tmp)
{
a[k + gap] = a[k]; // 将在a[i]前且比tmp的值大的元素向后移动一位
k -= gap;
}
a[k + gap] = tmp;
}
}
//函数实现功能:折半查找数x,若找到返回存在数量,未找到则返回-1
int binary_search(int a[], int x, int len)
{
int left = 0;
int right = len - 1;
int tmp = 0;
int e = 0, f = 0, n = 0;
while (left < right)
{
tmp = (right + left) / 2; //进行每次折半操作
if (x > a[tmp])
left = tmp;
if (x < a[tmp])
right = tmp;
if (x == a[tmp])
{
int n = 1;
int i = 1;
while (1)
{
if (tmp + i == len)
break;
if (x == a[tmp + i])
{
n++;
i++;
}
else break;
}
i = 1;
while (1)
{
if (tmp - i == - 1)
break;
if (x == a[tmp - i])
{
n++;
i++;
}
else break;
}
return n;
}
//跳出奇异点
if (e == left && f == right)
n++;
if (n == 2)
break;
e = left; f = right;
}
return -1;
}