What went wrong? - sorting array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include<iostream>
#include<utility>

using namespace std;

int main()
{
    const int size = 6;
    int array[size] = { 30, 60, 20, 50, 40, 10 };


    for(int startIndex = 0; startIndex < size; startIndex++)
    {

        int smallestIndex = startIndex;
        for(int currentIndex = startIndex+1; currentIndex<size; currentIndex++)
        {

            if(array[currentIndex] < array[smallestIndex])
            {
                swap(currentIndex, smallestIndex);
            }


        }

        for(int i=0; i<size; i++)
            cout<<array[i]<<" ";

         cout<<"\n";
    }
    
    
}


Outputs:
30 60 20 50 40 10
30 60 20 50 40 10
30 60 20 50 40 10
30 60 20 50 40 10
30 60 20 50 40 10
30 60 20 50 40 10
swap(currentIndex, smallestIndex);

^ That part there, I do believe.

EDIT: You're going to laugh when you see it, and I'm not too proud to admit that I looked at it longer than I should have (and even started writing it down) before I said, "Oh my God..." It's pretty humorous, when you see it.

But you should really look into vector. This entire thing could have been summed up:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <vector>
#include <algorithm> //for sort
using namespace std;

int main() {
vector<int> v{ 30, 60, 20, 50, 40, 10 };
sort(v.begin(), v.end());
for(int i:v) cout << i << ' ';
cout << endl; 
}
Last edited on
Wow that's pretty simple! But I haven't learned vectors yet, so just need to finding my mistake in the selection sort using arrays method
Yeah, it's really simple. Far simpler than dealing with arrays.

And if you're still not sure where the mistake is, take a look at your swap function. Ask yourself, "What values do I want to swap?" then look at the values in the swap function and ask yourself what values are ACTUALLY being swapped.
Topic archived. No new replies allowed.