Your code *almost* compiles, but you forgot to paste the appropriate #include in your post. If you make your code 100% compileable in the future, it'll help others help you faster.
As you mentioned, the output is always [10, 1, 2, 3, 4, 5, 6, 7, 8, 9]. Here's a trick: Use the output of the code as the input for your debugging. Figure out why the first index is never changing when it's 10.
Another trick is to simplify your input. Perhaps 10 numbers is too tedious to go through by hand. Simplify down to a smaller number. Factor out all instances of "10" in your program to a named constant:
const int NumElements = 10; , then change that to say, 2 or 3.
1 2 3 4 5 6 7 8
|
const int NumElements = 2;
int unsorted_num[NumElements] = { 10 , 1 };
for ( int x = 0; x <NumElements; x++ )
{
for ( int y = 1; y<NumElements; y++)
{
...
|
You'll find that your code still has the same problem!
Input: {10, 1}
Output:
Your code is checking if array[x] < array[y] for some combination of x and y, and switching them if so. The issue with that is, there are times
(such that when x < y) where array[x] < array[y] is a "good" thing, and you don't want to sort them.
In other words, your code is almost correct, but you need to account for 2 things:
- 1. (arr[x] < arr[y]) for x < y is already "sorted" (at least, that part of the array)
- 2. (arr[x] > arr[y]) for x < y is NOT sorted. (actually, this is the same thing, just the inverse statement)
PS: The following won't affect the logic of your program, but is about readability: Naming your array "unsorted_num" can be misleading, because your array will (hopefully) be sorted by the time you print it out in your last for loop. Similarly, the variable called "max_num" is sort of misleading, because you are assigning unsorted_num[x] to it, which will already be less than unsorted_num[y]. In reality, you are just using "max_num" as a temporary swap variable, so it's perfectly fine to call it something like:
1 2 3
|
int temp = nums[x];
nums[x] = nums[y]
nums[y] = temp;
|
This also keeps 'temp' in the narrowest scope possible. But again, this is just small tips for the future.