GG Bro
GG Bro

Reputation: 65

Selection sort to find the largest number in an unsorted array

I am trying to sort an array to find the largest number and move it to the end and swapping it with the current element there. What am I actually doing wrong? I've tried to watch videos of this but all of them is just sorting the array to find the smallest element.

#include <iostream>
using namespace std;
int main(){
    int const LENGTH = 10;
    int myList[LENGTH] = {2, 56, 34, 25, 73, 46, 89,10, 5, 16};
    int i, x, max, temp;
    for(i=0; i< 10;i++)
    {
        int max = i;
        for(int j=i+1; j <10; j++)
        {
            if(myList[max] < myList[j])
            {
                max = j;
            }
        }
        temp = myList[max];
        myList[max] = myList[i];
        myList[i] = temp;
        for(x=0;x<10;x++)
        {
            cout << myList[x] << " ";
        }
        cout << endl;
    }
    return 0;
}

For some reason my code outputs this, Its fine buts its backwards

89 56 34 25 73 46 2 10 5 16
89 73 34 25 56 46 2 10 5 16
89 73 56 25 34 46 2 10 5 16
89 73 56 46 34 25 2 10 5 16
89 73 56 46 34 25 2 10 5 16
89 73 56 46 34 25 2 10 5 16
89 73 56 46 34 25 16 10 5 2
89 73 56 46 34 25 16 10 5 2
89 73 56 46 34 25 16 10 5 2
89 73 56 46 34 25 16 10 5 2

Upvotes: 1

Views: 1477

Answers (2)

Reksotiv
Reksotiv

Reputation: 24

for (i = LENGTH-1; i >= 0; i--)    
   for (int j = i ; j >= 0; j--)

Upvotes: 0

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17415

When you're studying sorting algorithms, they usually start with the concept of a generalized ordering. Sorting numbers in ascending or descending order is just one possible such ordering. For that reason, e.g. std::sort() takes a function as parameter. That function simply takes two elements and tell the algorithm whether the first one should come before the second. Check out the according documentation, but keep in mind that it requires very careful reading, because often things are only implied.

Now, in your case, the ordering function is simply the less-than operator (<) which you use to compare elements. At the end, it causes every element N+1 to be less than element N. If you use a different operator, you will change ordering accordingly, so just use the greater-than operator to switch the order around.

Upvotes: 1

Related Questions