...

C++ Bubble Sort/Binary Search Help

jarrex
12-03-2008, 10:41 PM
side note: admin, for some reason it posted it in html at first... so feel free to delete it if you want.

So for my last assignment i have to create a program that allows the user to input 100 foods, enter calorie amount and then using bubble sort and binary search it has to be able to display them back to the user. I have all of this done except the food does not match up with the calories.

any help is greatly appreciated!!

#include <iostream>
#include <string>

using namespace std;

int main()
{
string foods [100];
string product;
double calories [100];
int counter = -1;
bool done1 = false;
bool done = false;
do
{
counter++;
cout << "Enter a menu item (enter 'done' when finished): ";
getline(cin,foods [counter]);
if (foods [counter] == "done"){
done1 = true;
}
else{
cout << "Enter the number of calories: ";
cin >> calories [counter];
cin.ignore();
}
} while (done1 == false);
int i;
int j;
string tmp;
//bubble sort
for (i=0; i<counter; i++) {
for (j=0; j<counter-i; j++)
if (foods[j+1]< foods[j]) {
tmp = foods[j];
foods[j] = foods[j+1];
calories[j] = calories[j+1];
foods[j+1] = tmp;
}
cout << foods[j] << " " << endl;
}
//end bubble sort, start binary search
while (done == false){
int upperbound = counter;
cout << "Enter a product to look up: ";
getline(cin,product);
if (product == "done"){
done = true;
break;
}
int lowerbound = 0;
int position;
position = ( lowerbound + upperbound) / 2;
while((foods[position] != product) && (lowerbound <= upperbound))
{
if (foods[position] > product)
{
upperbound = position - 1;
}
else
{
lowerbound = position + 1;
}
position = (lowerbound + upperbound) / 2;
}
if (foods[position] == product){
cout << foods[position] << " has " << calories[position] << " calories." << endl;
cout << foods[1] << calories[1] << position;
}
if (lowerbound > upperbound)
{
cout << product << " was not found." << endl;
}}

}

tomws
12-04-2008, 03:54 AM
Look at your bubble sort. You're only sorting the foods array.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum