How to use structs in binary search?

Refresh

February 2019

Views

22 time

0

I'm trying to learn c (its my first language) and i have some problems with this task. (It is no homework!)

Task:

Implement the binary search algorithm on an array of structs of the following kind (sorry for my English).

    struct {
    unsigned int number;
    char* food;
    int price; 
} pk;
  • The given array is sorted in ascending order
  • When the searched number is found, give <nr>: <food> <price>\n back
  • When the searched number isn't found, give <nr> is not in pk \n back and return -1

My code:

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


struct {
    unsigned int number;
    char* food;
    int price; 
} pk;


int binary search(int pk[], int l, int r, unsigned int number){
    int center;
    int start = l;
    int end = r;

    if (start == end){
        if (pk[start] == number){
            printf ("%d is in pk\n", number);   // do not know how to use the struct 
        }else{
            printf ("%d is not in pk\n", number);
            return -1;
        }
    }
    else {
        center = (start + end)/2;
        if (number <= pk[center]){
            return binary search(pk, start, center, number);
        }else{
            return binary search(pk, center+1, end, number);
        }
    }
}

My questions:
1) Could this code work?
2) How I can use this struct to fulfill the task, in my opinion I should to it complete different then now.

1 answers

0

Включить все предупреждения компилятора!

Когда if (start == end){ if (pk[start] == number){правда, код не возвращает ничего .

Я бы ожидать return start;в этом случае.


Избегайте start + endпереполнения

// center = (start + end)/2;
center = start + (end - start)/2;

Немного иначе:
я бы рекомендовал , чтобы вернуть указатель на массив на успех и NULLна неудачу

// int binary search(pk a[], int l, int r, unsigned int number){
pk *binary search(pk a[], int l, int r, unsigned int number){
    int start = l;
    int end = r;

    if (start == end){
        if (a[start].number == number){
            printf ("%d is in a[] at index\n", number, start);
            return &a[start];
        }else{
            printf ("%d is not in a[]\n", number);
            return NULL;
        }
    }
    else {
        int center = start + (end - start)/2;
        if (number <= a[center].number){
            return binary search(a, start, center, number);
        }else{
            return binary search(a, center+1, end, number);
        }
    }
}

Дополнительно: Лучше использовать код будет size_tдля индексации и аconst a[]

pk *binary search(const pk a[], size_t l, size_t r, unsigned int number){