Hi, I am having trouble getting the item and its calories to match. Could anyone tell me what is wrong with this bubble sort? Thanks

int main()
{
	string food[100];
	string search;
	int calories[100];
	int x = -1;
	bool look = false;
	do
	{
		x++;
		cout << "Enter a menu item (enter 'done' when finished): ";
		getline(cin, food[x]);
		if (food[x] != "done")
		{
			cout << "Enter the number of calories: ";
			cin >> calories[x];
			cin.ignore();
		}
	} 
	while (food[x] != "done");
	int i;
	int c;
	string tmp;
	//bubble sort
	for (i=0; i < x; i++)
	{
	for (c=0; c < x-i; c++)
		if (food[c+1]< food[c]) 
		{
			swap (food[c], food[c+1]);
		}
		if (calories[c+1] < calories[c])
		{
			swap (calories[c], calories[c+1]);
		}
	}
//binary search
	while (look == false)
	{
		int upper = x;
		cout << "Enter a product to look up: ";
		getline(cin, search);
		if (search == "done")
	{
		look = true;
		break;
	}
	int lower = 0;
	int pos;
	pos = ( lower + upper) / 2;
	while((food[pos] != search) && (lower <= upper))
	{
	if (food[pos] > search)
	{
		upper = pos - 1;
	}
	else
	{
		lower = pos + 1;
	}
	pos = (lower + upper) / 2;
	}
	if (food[pos] == search)
	{
		cout << food[pos] << " has " << calories[pos] << " calories." << endl;
	}
	if (lower > upper)
	{
	cout << search << " was not found." << endl;
	}
	}
}

I assume food and calories are parallel arrays meaning that food[x] has calories[x] calories and you want to keep the food matched with the correct calories and you are trying to alphabetize the food array. If that is the case then swap calories[x] and calories[x + 1} in the body if the same if. Likewise if you want to sort calories in ascending (or descending) order and you want to keep the food matched with the calorie value, then swap them in the body of the same if statement.

In your code what happens when i = 0 and c = x - i? Is c + 1 a valid index?

I assume food and calories are parallel arrays meaning that food[x] has calories[x] calories and you want to keep the food matched with the correct calories and you are trying to alphabetize the food array. If that is the case then swap calories[x] and calories[x + 1} in the body if the same if. Likewise if you want to sort calories in ascending (or descending) order and you want to keep the food matched with the calorie value, then swap them in the body of the same if statement.

In your code what happens when i = 0 and c = x - i? Is c + 1 a valid index?

Thanks for your help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.