如何找到这个递归的二进制搜索程序并且如果找不到该数字则不会崩溃?

时间:2014-10-11 08:25:57

标签: c recursion crash binary-search

如果找不到用户搜索到的值,如何防止此程序崩溃? (当我尝试实现if / else或count系统时,程序无法正常工作)

#include <stdio.h>
#include "simpio.h"
#include "genlib.h"
#define start 0
void bubble(int numbers[]);
int binary(int val, int numbers[], int low, int high);
void io(int numbers[]);
int size;
main()
{
    int result, search;
    printf("This program sorts and searches an array\n");
    printf("How many numbers would you like to sort and search?\n");
    size = GetInteger()-1;
    int numbers[size];
    printf("Enter the numbers\n");
    io(numbers);
    bubble(numbers);
    printf("Which number would you like to search for?\n");
    search = GetInteger();
    result = binary(search,numbers,start,size);
    printf("The number %d was found at index %d\n",search,result+1);
}

void io(int numbers[])
{
    int ink;
    for(ink=0;ink<=size;ink++)
    {
        numbers[ink] = GetInteger();
    }
}

void bubble(int numbers[])
{
    int first,second,count,swap;
    while(TRUE)
    {
        for(first=0,second=1,count=0;second<=size;first++,second++)
        {
            if(numbers[first]>numbers[second])
            {
                count++;
                swap = numbers[first];
                numbers[first]= numbers[second];
                numbers[second] = swap;
            }
        }
        if(count==0)break;
    }
}

int binary(int val, int numbers[], int low, int high)
{
    int mid;
    mid = (low+high)/2;
    if(val==numbers[mid]||low>high) return mid;
    if(val>numbers[mid]) return(binary(val,numbers,mid,high));
    else if(val<numbers[mid]) return(binary(val,numbers,low,mid));
}

1 个答案:

答案 0 :(得分:0)

更改为

size = GetInteger();
int numbers[size--];//change size to max index
//..

int binary(int val, int numbers[], int low, int high)
{
    int mid;
    if(low>high)//if not found!
        return -1;//check return value at main
    mid = (low+high)/2;
    if(val==numbers[mid]) return mid;
    if(val>numbers[mid]) return(binary(val,numbers,mid+1,high));
    else if(val<numbers[mid]) return(binary(val,numbers,low,mid-1));
}