sorting bug

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
#include<conio.h>
#include<iostream.h>
void  main()
{
clrscr();
int array[5],min,temp,i,loc,j;
for(i=0;i<5;i++)
{
cout<<"Enter the value of"<<"array["<<i<<"]";
cin>>array[i];
cout<<endl;
}
for(i=0;i<5;i++)
{
cout<<array[i]<<"  ";
}
for(i=0;i<4;i++)
{
min=i;
for(j=1+i;j<5;j++)
{
if(array[j]<array[min])
min=j;
if(min!=i)
{
temp=array[i];
array[i]=array[min];
array[min]=temp;

}
}
}
cout<<endl;
for(i=0;i<5;i++)
{
cout<<array[i]<<"  ";
}
getch();
}


output :
input 1 2 3 4 5 6
output 1 2 3 4 5 6 //correct

input 5 2 3 4 6
output 3 2 5 4 6 // worng

input 6 5 4 3 2 1
output 1 2 3 4 5 6 //correct

plz help why are 5 2 3 4 6 give worng result
Please indent your code. (some comments may help too)
Do a desk test, look carefully what are 'i', 'j', 'min' pointing.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// #include<conio.h> // not a standard C++ header
//#include<iostream.h> // not a standard C++ header
#include <iostream> 
using namespace std ;

// void  main() // main() must return int
int main() 
{
    // ...

   // for(i=0;i<4;i++) // what about array[4] ?
   for(i=0;i<5;i++)
   {
       min=i;

   // ...

}
By construction array[4] should end with the correct value.

One of the good things about selection sort is that you just need to do O(n) swaps of the objects. You kill that property.
Look carefully
1
2
3
4
5
6
7
8
if(array[j]<array[min])
  min=j;
if(min!=i)
{//swap( array[i], array[min] )
  temp=array[i];
  array[i]=array[min];
  array[min]=temp;
}
If you do the swap, then min will no longer point to the minimum element.
Topic archived. No new replies allowed.