Pagini recente » Cod sursa (job #3216095) | Cod sursa (job #2275019) | Cod sursa (job #2257072) | Cod sursa (job #1073448) | Cod sursa (job #1424863)
#include <stdio.h>
#include <stdlib.h>
int* Vector,N;
int BinarySearch(int Value);
int main()
{
int Index;
int i;
int Order, Value;
int M;
FILE* input;
FILE* output;
output = fopen("cautbin.out","w");
input = fopen("cautbin.in","r");
fscanf(input,"%d",&N);
Vector = (int*)malloc((N+2)*sizeof(int));
for(i=1; i<=N; i++) fscanf(input,"%d", Vector+i);
Vector[0]=-1;
Vector[N+1] = 2147483647;
fscanf(input,"%d",&M);
for(i=0; i<M; i++){
fscanf(input,"%d",&Order);
fscanf(input,"%d",&Value);
switch(Order){
case 0:
Index = BinarySearch(Value);
while(Vector[Index+1] == Value) Index++;
fprintf(output,"%d\n",Index);
break;
case 1:
Index = BinarySearch(Value);
while(Vector[Index+1] <= Value) Index++;
fprintf(output,"%d\n",Index);
break;
case 2:
Index = BinarySearch(Value);
while(Vector[Index-1] >= Value) Index--;
fprintf(output,"%d\n",Index);
break;
}
}
fclose(output);
fclose(input);
return 0;
}
int BinarySearch(int Value)
{
int Left,Right,Index;
Left = 1;
Right = N;
while(Left < Right - 1)
{
Index = Left + (Right-Left)/2;
if(Vector[Index] < Value) Left = Index;
else if(Vector[Index] > Value) Right = Index;
else if(Vector[Index] == Value) return Index;
}
if(Vector[Left] == Value) return Index;
if(Vector[Right] == Value) return Index;
return -1;
}