简体   繁体   中英

Binary Search and Sorting - CS50 Find pset3

I'm trying to implement a binary search after doing a selection sort for CS50, pset3 find.

I feel that my logic is correct, but I don't know where my code is wrong. Below is my code.

Error List

#include <cs50.h>

#include "helpers.h"

#define RANGE 65536

/**
 * Returns true if value is in array of n values, else false.
 */
bool search(int value, int values[], int n)
{
    // TODO: implement a searching algorithm
    //binary search
    int midpoint =  ((0 + (n-1))/2);

    while (n  > 0)
    {
        if (value == values[midpoint])
        {
        return true;
        }
        else if (value < values[midpoint]){
        midpoint = ((0 + (midpoint-1))/2);
        }
        else if  (value > values[midpoint]){
        midpoint = (((midpoint+1) + (n-1))/2);
        }
        if (value != values[midpoint])
        {
        return false;
        }
    }
   return false;
}

/**
 * Sorts array of n values.
 */
void sort(int values[], int n)
{
    // TODO: implement a sorting algorithm
    //selection sort
    for (int i = 0; i < n; i++)
    {
        int min = i;

        for (int j = i+1; j < n; j++)
        {
            if(values [j]< values[min])
            {
              min = j;
            }
            if(min != i)
            {
              int exchange = values [min];
              values [min] = values [i];
              values [i] = exchange;
            }
        }
    }
    return;
}

Basically, I think my logic is mostly correct, but again, I'm not too sure. I am still a beginner so I get caught up in the simplest errors sometimes. Any help would be greatly appreciated.

The function is wrong.

For example it can be executed infinitely. Let's assume that n is equal to 1. In this case initially midpoint

int midpoint =  ((0 + (n-1))/2);

will be set to 0. If value is less than values[0] then again due to this if statement

    else if (value < values[midpoint]){
    midpoint = ((0 + (midpoint-1))/2);
    }

midpoint will be set to 0. And this part of the function will be repeated again and again.

Also the calculation of midpoint in this if statement

    else if  (value > values[midpoint]){
    midpoint = (((midpoint+1) + (n-1))/2);
                                ^^^^^
    }

is wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM