Sorting a vector without using sort

I have a vector, called sVec, containing the IDs of students and I want to sort them in numerical order. This is what I did so far but it only sorts some of the IDs in order. How can I improve this loop to make it sort the entire vector?

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

 for (int i = 0; i < sVec.size(); i++)
 {
  miniPos = i;
  for (int j = i + 1; j < sVec.size(); j++)
  {
   if (sVec[j] < sVec[i])
   {
    miniPos = j;
   }
  }

  temp = sVec[miniPos];
  sVec[miniPos]= sVec[i];
  sVec[i] = temp;
 }


Last edited on
Perhaps you should review your documentation for the sort you're trying to implement and insure you have the concepts implemented correctly.

Why are you "swapping" an element after the loops, shouldn't that be inside the if() statement within the loop?

No, he is doing the swap in the outer loop like it should be. You are comparing sVec[j] with sVec[i].

You should be comparing sVec[j] with sVec[miniPos]. You don't care if it's less than position i, you care if it's smaller then the smallest you've found thus far!

Edit - > Just for completeness...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
	int miniPos;

	for (int i = 0; i < sVec.size(); i++)
	{
		miniPos = i;
		for (int j = i + 1; j < sVec.size(); j++)
		{
			if (sVec[j] < sVec[miniPos]) //Change was here!
			{
				miniPos = j;
			}
		}

		temp = sVec[miniPos];
		sVec[miniPos] = sVec[i];
		sVec[i] = temp;
	}
Last edited on
Topic archived. No new replies allowed.