Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > C/C++ программирование > Общие вопросы C/C++
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 07.11.2015, 14:49   #1
Kengoo
Пользователь
 
Регистрация: 05.09.2015
Сообщений: 16
По умолчанию Binary Search

нужно отобразить значения first, last, middle на каждой стадии цикла и кол-во сравнений. кол-во сравнений неправильно отображает. подскажите пжл где ошибка

Код:
#include <iostream>
 
using namespace std;
 
int binary(int list[], int length, int item)
{
    int first = 0;
    int last = length - 1;
    int mid;
    bool found = false;
    int count=0;
        
    while (first <= last && !found )
    {
        count++;
        
        mid = (first + last) / 2;
        cout << endl;
        cout << "Iteration " << count << endl;
        cout << " Middle - Index " << mid << endl;
        cout << " Middle - Value " << list[mid]<< endl;
        
        if (list[mid] == item)
        {
            found = true;
            
        }
        else if (list[mid] > item)
        {
            last = mid - 1;
            cout << " Last - Index " << last << endl;
            cout << " Last " << list[last] << endl;
        }
        else
        {
            first = mid + 1;
            cout << " First - Index " << first << endl;
            cout << " First " << list[first] << endl;
        }
        
    }
        
    cout << "Comparisons " << count << endl;
        
    if (found)
    {
        return mid;
    }
    else
        return -1;
    }
 
int main()
{
    int inlist[] = { 5, 12, 25, 32, 38, 46, 58, 62, 85, 90, 97, 105, 110 };
    int ilist[] = { 4, 8, 19, 25, 34, 39, 45, 48, 66, 75, 89, 95 };
    int a = sizeof(inlist) / sizeof(int);
    int b = sizeof(ilist) / sizeof(int);
    int num;
    
    
        cout << "Enter a number " << endl;
        cin >> num;
        
        int pos;
        pos = binary(ilist, b, num);
 
        if (pos != -1)
        {
            cout << "The value is found at the position  " << pos << endl;
        }
        else
            cout << "The value is not in the list " << endl;
    
    system("pause");
    return 0;
}
Kengoo вне форума Ответить с цитированием
Старый 07.11.2015, 14:59   #2
Kengoo
Пользователь
 
Регистрация: 05.09.2015
Сообщений: 16
По умолчанию

починил

Код:

#include <iostream>

using namespace std;

int binary(int list[], int length, int item)
{
	int first = 0;
	int last = length - 1;
	int mid;
	bool found = false;
	int count=0;
		
	while (first <= last && !found )
	{
		
		
		mid = (first + last) / 2;
		cout << endl;
		cout << "Iteration " << count << endl;
		cout << " Middle - Index " << mid << endl;
		cout << " Middle - Value " << list[mid]<< endl;
		
		if (++count && list[mid] == item)
		{
			found = true;
			
		}
		else if (++count && list[mid] > item)
		{
			last = mid - 1;
			cout << " Last - Index " << last << endl;
			cout << " Last " << list[last] << endl;
		}
		else
		{
			first = mid + 1;
			cout << " First - Index " << first << endl;
			cout << " First " << list[first] << endl;
		}
		
	}
		
	cout << "Comparisons " << count << endl;
		
	if (found)
	{
		return mid;
	}
	else
		return -1;
	}

int main()
{
	int inlist[] = { 5, 12, 25, 32, 38, 46, 58, 62, 85, 90, 97, 105, 110 };
	int ilist[] = { 4, 8, 19, 25, 34, 39, 45, 48, 66, 75, 89, 95 };
	int a = sizeof(inlist) / sizeof(int);
	int b = sizeof(ilist) / sizeof(int);
	int num;
	
	
		cout << "Enter a number " << endl;
		cin >> num;
		
		int pos;
		pos = binary(ilist, b, num);
		

		
		if (pos != -1)
		{
			cout << "The value is found at the position  " << pos << endl;
		}
		else {
			cout << "The value is not in the list " << endl;

		}
	
	system("pause");
	return 0;
}
Kengoo вне форума Ответить с цитированием
Старый 07.11.2015, 15:01   #3
Stilet
Белик Виталий :)
Старожил
 
Аватар для Stilet
 
Регистрация: 23.07.2007
Сообщений: 57,097
По умолчанию

Цитата:
кол-во сравнений неправильно отображает.
Видимо нужно так:
Код:
 while (first <= last && !found )
    {
        
        
        mid = (first + last) / 2;
....

        else if (list[mid] > item)
        {
            last = mid - 1; count++;
...
        }
        else
        {
            first = mid + 1; count++;
...
        }
        
    }
I'm learning to live...
Stilet вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
error C2679: binary '>>' krivou Общие вопросы C/C++ 31 21.09.2015 13:40
В приложении Исчезают файлы Binary V.G.Ch Microsoft Office Excel 1 27.02.2012 17:33
Program binary formats f.hump Gamedev - cоздание игр: Unity, OpenGL, DirectX 2 18.01.2012 11:46
BST - Binary Search Tree Swool Общие вопросы C/C++ 1 15.10.2009 17:03