### Thread: sorting algorithm

1. #### sorting algorithm

I have an assigment in which we were given a flowchart to trace and write a sorting algorithm from it. we have to follow the flowchart exactly, meaning the loops, variables, and functions have to be what we were told to use.

anyway, i wrote this program for the user to enter a 3 digit number and have it sorted so it will be printed in reverse. for instance, if the user enter 123, the out put would be 321.

i can get the program to compile, but it will hang if i enter digits incorrectly, or only give me a chance to enter 2 digits instead of three.

like i said i have to follow and use the functions that i specify. here is the code:

Code:
```#include<iostream.h>

void sort(int);
void move(int, int &);
void Findit(int, int, int &);

int a[10];

void main() {
int n;
cout<<"Enter the number of digits to sort (2-10): ";
cin>>n;
cout<<"Enter "<< n <<" digits separated by a space: ";
for (int i=1;i<n+1;i++)
cin>>a[i];
cout<<endl;
sort(n);
cout<<"The values you entered are: ";
for (i=1;i<n+1;i++)
cout<< " " << a[i];
}

void sort(int s)
{
int j;
for(j=1;j<s-1;j++) {
if (a[j] > a[j+1]) {
move(s,j);
}
}return;
}

void move(int x, int &p)
{
int T,k;
T=a[p-1];
a[p+1]=a[p];
Findit(T,p,k);
a[k]=T;
}

void Findit(int W, int i, int &p)
{
int j=i, s=0;
while ((j>1) && (s=0)) {
if (a[j-1]>W)
{
a[j]=a[j-1];
j=j-1;
}
else s=1;
}
return;
}```
Last edited by webblynx; September 23rd, 2003 at 09:55 PM.
2. array indexes start from 0. so, when you declare:
Code:
`int a[3];`
the first element is a[0], the 2nd a[1], and the 3rd a[2]. hope that helps.
3. I think you have a lot of other bugs in your code. When posting here, please encose your tags in "code" tags.
4. okay, i made some changes, and it seems to be working better now, but it still isn't sorting.

the values i enter come out exactly as i enter them, and not in reverse order.
5. #### Re: sorting algorithm

Code:
```void Findit(int W, int i, int &p)
{
int j=i, s=0;
while ((j>1) && (s=0)) { //this should be (s == 0) as (s = 0) is always true.
if (a[j-1]>W)
{
a[j]=a[j-1];
j=j-1;
}
else s=1;
}
return;
}```
a good place to start debugging is inserting trace statements in your code. perhaps they would output the value of a variable or the result of a test. then you make verify that your code is doing what you think it is.