1

I'm a super noob at c++. For some reason this sorting code wont work, any help would be great thanks! The method i'm attempting to use is selection sort.

#include "stdafx.h" #include <algorithm> #include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { const int nTotalSize = 5; int data[nTotalSize] = { 7, 47, 1, 8, 2 }; for (int iii = 0; iii < 5; iii++) { int nCurrentSmall = iii; for (int jjj = iii+1; jjj < nTotalSize; jjj++) { if (data[jjj] < data[iii]) { nCurrentSmall = jjj; } } swap(data[iii], data[nCurrentSmall]); } for (int iii = 0; iii < 5; iii++) { cout << data[iii] << endl; } return 0; } 
3
  • What does "won't work" mean? What issues are you facing? Commented Dec 25, 2014 at 8:51
  • The code will compile but it produces the output of 2,7,1,8,47. Apologies for lack of details. Commented Dec 25, 2014 at 8:52
  • Ok. Have you tried debugging it at all? How about something simple like printing the value of data[iii] after the swap and checking if it matches expectations? Commented Dec 25, 2014 at 8:55

3 Answers 3

1

I've made some simple modifications...

#include "stdafx.h" #include <algorithm> #include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { const int nTotalSize = 5; int data[nTotalSize] = { 7, 47, 1, 8, 2 }; for (int iii = 0; iii < nTotalSize-1; iii++) { int nCurrentSmall = iii; for (int jjj = iii+1; jjj < nTotalSize; jjj++) { if (data[jjj] < data[nCurrentSmall]) { nCurrentSmall = jjj; } } swap(data[iii], data[nCurrentSmall]); } for (int iii = 0; iii < 5; iii++) { cout << data[iii] << endl; } return 0; } 
Sign up to request clarification or add additional context in comments.

Comments

1

Hint: when looking for the smallest element, you need to be comparing against the smallest value seen so far. You are comparing against something else.

Comments

1

You defined:

int nCurrentSmall = iii; 

but you didn't use it as it should be used in selection sort.

 if (data[jjj] < data[iii]) { nCurrentSmall = jjj; } 

This is used to compare indexes of data[iii] to every element data[jjj] and change the index of iii with the index of the current item when the element is smaller than the current item, but since you're comparing data[iii] the whole time, it's not working because the value getting changed is nCurrentSmall, and the value of nCurrentSmall should also be the value of iii as well to reflect the changes. Change it to this:

 if (data[jjj] < data[nCurrentSmall]) { nCurrentSmall = jjj; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.