Thursday, July 30, 2009

Sorting 2 arrays with C++?

My assignment is to create a program using 2 arrays. The first array asks for an ID number and the second array is to input a donation amount, and then to sort them so it outputs the IDs in numerical order with the corresponding donation amount. I already have the algorithm to sort the ID numbers figured out but when it outputs, the donations dont match up to the correct id numbers. Please help. this has to done with 2 arrays, it cant be done with a struct or anything else.

Sorting 2 arrays with C++?
Change the code so that every time the sort swaps values in the ID array, swap the values in the Donation Array.





Example:


void bubble_sort(int* a1 , int* a2)


{


int i, j, flag = 1; // set flag to 1 to begin initial pass


int temp; // holding variable


int arrayLength = sizeof(a1)/sizeof(int);


for(i = 1; (i %26lt;= arrayLength) %26amp;%26amp; flag; i++)


{


flag = 0;


for (j=0; j %26lt; (arrayLength -1); j++)


{


if (a1[j+1] %26gt; a1[j])


{


temp = a1[j]; // swap elements


a1[j] = a1[j+1];


a1[j+1] = temp;





temp = a2[j]; // swap elements


a2[j] = a2[j+1];


a2[j+1] = temp;


flag = 1; // indicates that a swap occurred.


}


}


}


return; //arrays are passed to functions by address; nothing is returned


}





}
Reply:You have to devise a method of keeping the two arrays in sync with each other so that after the IDs are sorted, the donations still relate to them correctly. There are several ways of doing this:





1. If you're moving the IDs when you sort them, move the donations the same way at the same time.


or


2. Don't actually move anything, but have a third array that contains the ORDINAL of the IDs/donations in the sorted order. That is, each entry in the sorted array contains the ordinal of the ID and its donation (never moved) in the sorted order. When you sort by ID, you only move ordinals. It's a lot trickier than the first, but it more accurately reflects real-world sorts.





Hope that helps.
Reply:Change the sort function to take both arrays. Do comparisons on the IDs and swaps on both arrays.





Here's a sort routine that you can modify:


http://xoax.net/comp/cpp/console/Lesson2...
Reply:you will find the answer @ http://www.planet-source-code.com

pokemon cards

No comments:

Post a Comment