#include <stdio.h>
#include <stdlib.h>
int erfenfa(int *p, int len, int target)
{
int left = 0;
int right = len - 1;
int i;
int j;
int tmp;
for (i = 0; i < len; i++)
{
for (j = 0; j < len-1-i; j++)
{
if (p[j] > p[j + 1])
{
tmp = p[j];
p[j] = p[j + 1];
p[j + 1] = tmp;
}
}
}
while (left <= right)
{
int mid = (left + right) / 2;
if (p[mid] == target)
{
return mid;
}
else if (p[mid] < target)
{
left = mid + 1;
}
else if (p[mid] > target)
{
right = mid - 1;
}
}
return left;
}
int main()
{
int len;
int target;
int k;
scanf_s("%d", &len);
scanf_s("%d", &target);
int* p = (int*)malloc(sizeof(int) * len);
if (p == NULL)
{
return 1;
}
else
{
for (k = 0; k < len; k++)
{
scanf_s("%d", p + k);
}
int index = erfenfa(p, len, target);
printf("%d", index);
free(p);
}
return 0;
}
结果
数组中有四个元素,找到元素5的索引,输入数组中的元素排列没有顺序。