Selection Sort

Hi! I'm trying to learn the selection sort, but I can't seem to make this work. Can someone tell me whats wrong with this? Thanks!

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <iostream>


using namespace std;


int GetSmallestIndex(int* numArray,int min,int max);


int main()
{
   int n=5;
   int numArray[n];

   for(int i=0;i<5;++i)
   {
       cout<<"Enter a number:";
       int temp;
       cin>>temp;
       numArray[i]=temp;
   }

   int p;
   for(int i=0;i<=n-1;++i)
   {
       p=GetSmallestIndex(numArray,i,n-1);
       cout<<numArray[p]<<endl;;
       int temp=numArray[i];
       numArray[i]=numArray[p];
       numArray[p]=temp;
      
   }
   

 
   for(int i=0;i<5;++i)
   {
      cout<<numArray[i]<<endl;
   }

  

    system("PAUSE");
}





int GetSmallestIndex(int* numArray,int min,int max)
{
    int smallest=numArray[0];
    int index;
    for(int i=min;i<=max;++i)
    {
          if(numArray[i]<smallest)
	  {
	       smallest=numArray[i];
	       index=i;
	  }
	  else continue;	    
    }

    return index;
}
1
2
3
4
5
6
7
8
9
10
11
int GetSmallestIndex( const int* numArray, int min, int max )
{
    int index = min;

    for( int i = min + 1; i <= max; ++i )
    {
          if ( numArray[i] < numArray[index] ) index = i;
    }

    return index;
}
Hi! It works now! Thanks! But can you explain whats wrong with what I did above?
In your function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int GetSmallestIndex(int* numArray,int min,int max)
{
    int smallest=numArray[0];
    int index;
    for(int i=min;i<=max;++i)
    {
          if(numArray[i]<smallest)
	  {
	       smallest=numArray[i];
	       index=i;
	  }
	  else continue;	    
    }

    return index;
}


you set the smallest initially to numArray[0]. It iis incorrect because you have to find the smallest among elements of the array in the range numArray[min] and numArray[max]. Also the initial value of index is undefined. So when the zero alement is the smallest in the whole array the function will always return the undefined index because it will assume that the zero element is the smallest.
Last edited on
Topic archived. No new replies allowed.