messed up sort
archer86 (15)Jan 6, 2009 at 6:15am UTC
Can anyone shed some light as to why this small sort program doesn't work properly?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<iostream>
using namespace std;
double swap (int [ ], int , int );
main(){
int slot[10]={8,3,1,5,7,10,4,9,6,2};
int n=10,i;
int lower, upper, sortflag, sml, scan;
lower=0;
upper=n-1;
sortflag=1;
while ((lower<upper)&&(sortflag==1)){
sml=lower;
sortflag=0;
scan=lower+1;
while (scan<=upper-lower){
if (slot[scan]>slot[scan+1]){
swap(slot,scan,scan+1);
sortflag=1;
if (slot[scan]<slot[sml]) sml=scan;
}//IF
scan++;
}//WHILE
swap(slot,lower,sml);
upper=upper-1;
lower=lower+1;
}//WHILE
cout<<"AFTER SORT:" <<endl;
for (i=0;i<n;i++) cout<<slot[i]<<" " ;
cout<<endl;
return 0; }//MAIN
double swap(int slot[], int i,int j){
int temp;
temp=slot[i];
slot[i]=slot[j];
slot[j]=temp;
return 0; }//SWAP
The output is: AFTER SORT: 0 1 3 4 5 6 7 2 9 8 Thanks in advance. C:\Dev-Cpp>
CamelCase (10)Jan 6, 2009 at 6:15am UTC
I just ran it on my system compiled with code::blocks, it ran fine output is 1 2 3 4 5 6 7 8 9 10...
dgirdhar (5)Jan 6, 2009 at 6:15am UTC
I also tried, it is working fine on my machine too.
Grey Wolf (639)Jan 6, 2009 at 6:15am UTC
Just looking over the code, Line 17,
while (scan<=upper-lower){ would allow scan to go to a value of 9, you then look at slot[scan+1] , which is out of bounds for slot and would result in unpredicable behavour. Try this: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
#include<iostream>
using namespace std;
double swap (int [ ], int , int );
int main()
{
int slot[10]={8,3,1,5,7,10,4,9,6,2};
int n=10;
int i = 0;
int lower = 0;
int upper = n-1;
int sortflag = 1;
while ((lower < upper) && ( sortflag==1))
{
sortflag = 0;
int sml = lower;
int scan = lower;
while (scan < upper )
{
if (slot[scan] > slot[scan+1])
{
sortflag = 1;
swap(slot,scan,scan+1);
if (slot[scan]<slot[sml])
sml=scan;
}
++scan;
}
swap(slot,lower,sml);
--upper;
++lower;
}
cout<<"AFTER SORT:" <<endl;
for (i=0; i<n; i++)
cout<<slot[i]<<" " ;
cout<<endl;
return 0;
}
double swap(int slot[], int i, int j)
{
int temp;
temp = slot[i];
slot[i] = slot[j];
slot[j] = temp;
return 0;
}
Last edited on Jan 6, 2009 at 6:15am UTC
This topic is archived - New replies not allowed.