Bubble sort 2 corresponding array

Jun 19, 2013 at 10:05am
Hi,

Just wondering, how can I bubble sort 2 corresponding array?
For example, I have an array of string called Items and array of float called price and these arrays are related to each other (i.e. items[0] relates to price[0]). I want to sort the item based on the price from lowest to highest and both arrays need to still be aligned to each other after the search

Thanks in Advance
Jun 19, 2013 at 10:09am
Just implement the bubble sort as normal but when you swap two items in the array, do the same, at the same position, in the other array.
Last edited on Jun 19, 2013 at 10:13am
Jun 19, 2013 at 11:17am
If you find yourself trying to maintain several parallel arrays, it's usually a sign that what you really want is a struct, or a class, which combines those things into a single type, e.g.

1
2
3
4
5
struct Item
{
  std::string itemName;
  float       price;
}


Then you can have a single array of structs:

 
Item items[NUM_ITEMS];

You can then sort the array based on the price, without having to worry about also updating another array to match the new order.
Last edited on Jun 19, 2013 at 11:18am
Jun 19, 2013 at 2:22pm
std::map<float,string> will help you to get it done easily.

myMap<price, name> is the easiest way!!
Topic archived. No new replies allowed.