Hello,

I need to complete a selection sort (descending order) on a string that contains 3 letters and one number. This is the function I wrote so far, but it doesn't sort properly. It is sorting, but I can't figure out its scheme. Any tips? Thanks! (The arrays are parallel. I just have to sort the id[] array and keep the gpa[]array connected to the right id.)

``````void Sort_Arrays(string id[], float gpa[], int listSize)
{

int index,    // location of last index that has been sorted
largestIndex = 0,   // location of largest index in unsorted portion
maxIndex = 0;  // max index from entire list, moved to top position
string temp1;
float temp2;

for (index = 0; index < listSize - 1; index++)
{

largestIndex = index; // assuming 1st index is largest

for (maxIndex = index + 1; maxIndex < listSize; maxIndex++)
{
if (id[maxIndex] > id[largestIndex])
largestIndex = maxIndex;
}

temp1 = id[largestIndex];
temp2 = gpa[largestIndex];
id[largestIndex] = id[maxIndex];
gpa[largestIndex] = gpa[maxIndex];
id[maxIndex] = temp1;
gpa[maxIndex] = temp2;

}

}``````

## All 5 Replies

Does the id array sort properly ? If not then you need to rethink the algorithm. Get that array sorted correctly first then you can add the code to swap the other array at the same time the id array elements are swapped. If you need a selection sort algorithm just use google and you will find lots of them.

The id array doesn't sort properly. (Actually, the swapping does work). The id array stores, for example, WAS3, HGR2, MMB1, WAS2...I want it to sort as WAS3, WAS2, MMB1, HGR1. So I want it to sort according to the first letter in the string and also according to the last number.

I am searching google now. :-)

In the swap step, you're swapping with maxIndex when you should be swapping with index.

I think you can ignore the last letter thing -- just sort according to normal descending sort rules and the last letter will fall in line correctly.

Thank you! I thought my problem was in the sorting and not swapping. :-( I swapped using index and that solved my problem. Thank you! *HUGS*

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.