简体   繁体   中英

Selection sort in C++ issue

I'm writing a program for my data structures course and I have run into an issue where my selection sort only seems to be running once. It is being used to organize an array by part number.

Here's the code for it:

    void sorter::selection ()
{
int i, last, large;
int temp;
for (last = maxSize-1; last >= 1; last --)  {  //maxSize = 20
large = last;
for (i=0; i < last; i++)
if (group[i].partNumber > group[large].partNumber)
large = i;
                                             }
temp = group[large].partNumber;
group[large].partNumber = group[last].partNumber;
group[last].partNumber = temp;
}

And here's the output:

Part Number     
278          
142         
427        
255          
562            
442           
980           
6          
992           
54           
550           
227          
2           
31           
24          
540           
766           
990           
101            
5          

It should be taking the largest value and placing it last in the array, and repeating that until everything is in its place...but it doesn't. Does anyone have ideas as to what I'm doing wrong here? Thanks!

The closing brace for your outer for loop is in the wrong spot. This is a good example of why proper indentation is so important. Try this version:

void sorter::selection()
{
    int i, last, large;
    int temp;
    for (last = maxSize-1; last >= 1; last --)
    {
        large = last;
        for (i=0; i < last; i++)
        {
            if (group[i].partNumber > group[large].partNumber)
                large = i;
        } // previously your outer loop ended here!
        temp = group[large].partNumber;
        group[large].partNumber = group[last].partNumber;
        group[last].partNumber = temp;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM