# Sort code not functioning properly

My sort code seems to be implemented correctly, however, it sorts based on the first digit in the number, rather than the number itself. any idea what the problem could be? this is some output...

``````jharvard@appliance (~/Dropbox/pset3/find): ./generate 10 1 | sort

115
12293
22019
24004
2728
29785
37059
49184
54710
64909
``````

``````    void sort(int values[], int n)
{
for (int i = 0; i < n-1; i++)
{
int swaps = 0;
for (int k = 0; k<n-1-i; k++)
{
if(values[k]>values[k-1])
{
int t = values[k+1];
values[k+1] = values[k];
values[k] = t;
swaps++
}
}
if (swaps == 0)
break;

}
}
``````
• you need to point us at the source code. – gitterb Mar 17 '15 at 1:23
• added source code – iluvpool19 Mar 17 '15 at 19:08

I think, you are using linux `sort` command instead of `sort` utility implemented by you.

Try using

``````./generate 10 1 | ./sort
``````

Assuming that you sort utility has name `sort`

I just tried your command and I get exactly the same result.

I didn't look closely before, but now I realize is that what you are doing is using the Linux `sort` command by using `| sort` (sort is sorting strings and therefore handles the numbers as strings)

In order to test your implementation of code is to use

`````` ./generate 10 1 | ./find 1
``````

then you will get them sorted correctly.

• It doesnt seem to be working – iluvpool19 Mar 18 '15 at 2:00

There are problems with the inner for loop. The loop should go from 0 to n-1, checking for greater of the two numbers everytime values[k] and values[k+1].

`````` for (int k = 0; k<n-1-i; k++)
{
if(values[k]>values[k+1])
{
int t = values[k+1];
values[k+1] = values[k];
values[k] = t;
swaps++
}
}
``````

Also you need the condition `(values[k]>values[k+1])` to check for which one of the two numbers is greater and not `(values[k]>values[k-1])`, since you are iterating from starting index(0) and values[0-1] is not defined. You could do the other way but again you meant to swap values[k] and values[k+1], so checking relation between values[k] and values[k-1] is illogical. The above snippet shall do the task.

Good Luck.