selection sort

Sep 10, 2008 at 4:30pm
Two questions here
1.When i run this selection sort function it is not sorting the whole vector. It is only sorting the first few

2.When i compile this i get a compiler warning "warning: comparison between signed and unsigned integer expressions". It is coming form my for loops. Is this something that can cause problems down the road and how could i fix this or write this function better?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

/*Selection sort will sort the vectors in ascending order*/
void selSort(vector<int>& v)
{
        int temp, min;

        for( int i = 0; i < v.size(); i++){
                min = i;
                for (int j = 1; j < v.size(); j++){
                        if (v[j] < v[min])
                        min = j;
                }
                temp = v[i];
                v[i] = v[min];
                v[min] = temp;
        }
}//end selection sort
Sep 10, 2008 at 4:37pm
v.size returns an unsigned int. I don't think it should cause a problem, but I can't say for sure.

In regards to your first question, print out vector at different points and make sure you aren't losing any values. I vaguely remember a similar problem I had when I was doing something like this and I was actually overwriting values rather than sorting them. I ended up with an array of about half the size I started with.
Last edited on Sep 10, 2008 at 4:37pm
Sep 10, 2008 at 4:59pm
It will only cause trouble when size() returns a value larger that INT_MAX (constant #define'd in climits). This value is usually no less than 2^31-1.

Your swap doesn't verify that min!=¡, so you might be swapping an element with itself at times.
Sep 11, 2008 at 12:55pm
The problem is that your inner for-loop is wrong, because it is considering too many elements. You know after the Nth iteration of the outer loop that the first N elements are sorted so the inner loop must not consider those, as they are guaranteed to be less than v[min].
Sep 11, 2008 at 2:33pm
Oh, look at that. I missed it.
The for i loop is also too long. It should be i<v.size()-1
Topic archived. No new replies allowed.