在C中将2个问题从线性搜索转换为二进制搜索?

时间:2018-06-02 21:42:12

标签: c search binary

基本上我已经遇到了2个线性搜索问题,我必须转换为二分搜索,而且我的C体验并不是很好。

#include <stdio.h>
#include <stdlib.h>

int functie ( int v[], int nr)
{
    int i, z=0;
    for(i=0;i<nr;i++) {
        if(z<v[i]) {
            z=v[i];
        }
    }
    return z;
}

int main()
{
    int i,nr;
    FILE *f;
    FILE *g;
    f=fopen("data-in.txt", "r");
    fscanf(f,"%d",&nr);
    int *v=malloc(nr*sizeof(int));
    for(i=0;i<nr;i++) {
        fscanf(f,"%d",&v[i]);
    }
    g=fopen("data-out.txt", "w");
    fprintf(g,"%d", functie(v,nr));
    fclose(f);
    fclose(g);
    free(v);
}

这是一个,它接受一个数组(例如:1 2 3 9 3 2 1)并显示所有内容都在升序之前的元素,然后一切都在下降(这种情况:9)

和另一个:

#include <stdio.h>
#include <stdlib.h>

int functie ( int v[], int nr, int y)
{
    printf("Numarul care trebuie verificat: \n");
    scanf("%d", &y);
    int i,count=0;
    for(i=0;i<nr;i++) {
        if(y==v[i]) {
            count=count+1;
        }
    }

    return count;
}

int main()
{
    int i,nr,y;
    FILE *f;
    FILE *g;
    f=fopen("data-in.txt", "r");
    fscanf(f,"%d",&nr);
    int *v=malloc(nr*sizeof(int));
    for(i=0;i<nr;i++) {
        fscanf(f,"%d",&v[i]);
    }
    g=fopen("data-out.txt", "w");
    fprintf(g,"Numarul apare de: %d ori", functie(v,nr,y));
    fclose(f);
    fclose(g);
    free(v);
}

计算元素在给定数组中出现的次数(例如:1 2 2 2 2 2 3 3 3 4 5 5 6 7 9 - 元素3出现3次)。

这个我尝试过编辑,我得到了这个:

#include <stdio.h>
#include <stdbool.h>
int BinarySearch(int A[], int n, int x,bool searchFirst)
{
    int low=0, high=n-1, result=-1;
    while(low<=high)
    {
        int mid= (low+high)/2;
        if(A[mid]==x)
        {
            result=mid;
            if(searchFirst)
                high = mid-1;
            low=mid+1;
        }
        else if(x<A[mid]) high=mid-1;
        else low=mid+1;
    }
    return result;
}

int main () {
    int nr,i;
    FILE *f;
    FILE *g;
    f=fopen("data-in.txt", "r");
    fscanf(f,"%d",&nr);
    int *A=malloc(nr*sizeof(int));
    for(i=0;i<nr;i++) {
        fscanf(f,"%d",&A[i]);
    }
    int x;
    printf("Enter number x:");
    scanf("%d", &x);
    int firstIndex=BinarySearch(A,sizeof(A)/sizeof(A[0]),x,true);
    if(firstIndex == -1)
    {
        g=fopen("data-out.txt", "w");
        fprintf("Count of %d is %d",x,0);
    }
    else
    {
        int lastIndex = BinarySearch(A,sizeof(A)/sizeof(A[0]),x,false);
        printf("Count of %d is %d",x,lastIndex-firstIndex+1);
    }
    fclose(f);
    fclose(g);
    free(A);
}

如果有人可以提供帮助,将非常感激

0 个答案:

没有答案