sorting an integer array

hello everyone, im new here trying to learn c++, i wrote a code to sort array but the out put always be like this [10, 1, 2, 3, 4, 5, 6, 7, 8, 9] i can't move 10 to be the last item in the array! here is the code.
int main()
{
int unsorted_num[10] ={5, 7, 2, 10, 3, 4, 6, 9, 8,1};
int max_num = 0 ;
for ( int x = 0; x <10; x++ )
{
for ( int y = 1; y<10; y++)
{
if(unsorted_num[x] < unsorted_num[y])
{
max_num = unsorted_num[x];
unsorted_num[x] = unsorted_num[y];
unsorted_num[y] = max_num;
}
}
}
std::cout<<"[";
for (int z =0; z<10;z++)
{
std::cout<< unsorted_num[z]<<" , ";
}
std::cout<<"]";
return 0;
}

thanks for your help
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:
[10 , 1 , ]


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.
Last edited on
trying to learn c++


Do you know about std::sort?
https://cplusplus.com/reference/algorithm/sort/
https://en.cppreference.com/w/cpp/algorithm/sort.html

Also, do you know about
https://www.learncpp.com/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <algorithm>
#include <iterator>

int main() {
	int nums[] { 5, 7, 2, 10, 3, 4, 6, 9, 8, 1 };

	auto show { [&nums]() {
		for (auto n : nums)
			std::cout << n << ' ';

		std::cout << '\n';
	} };

	show();

	std::sort(std::begin(nums), std::end(nums));

	show();
}



5 7 2 10 3 4 6 9 8 1
1 2 3 4 5 6 7 8 9 10


PS. Re swap. There is std::swap()
https://en.cppreference.com/w/cpp/algorithm/swap.html
https://cplusplus.com/reference/algorithm/swap/

For info on the Bubble Sort (which is what you're trying to do) see
https://www.geeksforgeeks.org/cpp/bubble-sort-in-cpp/
Last edited on
it's good to know that the standard library has those things for 'real' development, but as a practice exercise, figuring out a sort/swap on your own can be a good learning experience. When most people (here, at least) say they're "learning" C++, what they mean is that they're learning the basics of programming, and they're using C++ as that medium. But don't get me wrong, definitely good to know that features like auto, lambda captures, <algorithm>, and such exist.
thank you guys for your reply, i found the solution with comparing each 2 adjacent numbers.
thank you @seeplus for the new functions but im traying to make it manually to get more understanding
here is the solution, waiting for your comments as experienced programmers :)

#include <iostream>

int main()
{
int nums[10] ={5, 7, 2, 10, 3, 4, 6, 9, 8,1};
int max_num = 0 ;
for ( int x = 0; x <10; x++ )
{
for ( int y = x+1; y<10; y++)
{
if(nums[y] < nums[x])
{
max_num = nums[x];
nums[x] = nums[y];
nums[y] = max_num;
}
}
}
std::cout<<"[";
for (int z =0; z<10;z++)
{
std::cout<< nums[z]<<" , ";
}
std::cout<<"]";
return 0;
}
When posting code, please use code tags
[code]...[/code]
so that the code is readable.

Based upon the given code, consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <iterator>

int main() {
	int nums[] { 5, 7, 2, 10, 3, 4, 6, 9, 8, 1 };

	for (size_t x {}; x < std::size(nums); ++x)
		for (auto y { x + 1 }; y < std::size(nums); ++y)
			if (nums[y] < nums[x]) {
				const auto hold { nums[x] };

				nums[x] = nums[y];
				nums[y] = hold;
			}

	std::cout << "[";

	for (size_t c { std::size(nums) }; auto n : nums)
		std::cout << n << (--c ? ", " : "]\n");
}


Which displays:


[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


1) There is no need to specify the number of elements in an initialised array.
2) Use type size_t when dealing with number of objects/size etc.
3) Get into the habit of using pre-inc/pre-dec instead of post-inc, post-dec where appropriate. When you come onto overloading these operators for classes you'll understand the overhead of using post.
4) Where the type of an object is known, use auto.
5) Instead of using index to access an array element etc use a range-based for loop.
https://en.cppreference.com/w/cpp/language/range-for.html
6) If main() returns 0 there is no need for a return statement. For main() only no return is interpreted as return 0.
7) If the value of an initialised variable doesn't change mark it const.
8) Keep the scope of variables as small as possible and define as close as possible to it's usage.
9) Note the display loop which doesn't display an extra , after the last element is displayed.
Last edited on
hi @seeplus, thanks a lot for your reply i appreciate your help.
it seems i have missed a lot to learn, sorry for my poor demonstration of code but that's because i was learning C++ "beginner basics" 5 years ago on old version of it, then i stopped for some reasons but i love coding and trying to shift career, now i started with python as it is as known more easy than C++ and more required in business field but, sometimes when i stuck with python code i convert it to C++ code "the old version i learned" because i feel it is more detailed so i can see what is happening. now when i saw your code i got shocked, it seems there are many updates i missed, i was thinking to learn python parallel with C++ so i can get the simplicity of python and the C++ power what do you think? shall i proceed with both in parallel or stick with one language only? i have the logic and concepts of programming in general, i think the difference between programing languages is the syntax they all have the same logic (vars, loops, arrays, oop...) am i right?
please advise me with a road map to be software engineer if possible
many many thanks for you, appreciate your help
best regards
> shall i proceed with both in parallel or stick with one language only?

Certainly having in-depth experience with C++ and Python is good, long-term. I'm not sure where you are at as far as your own personal development. If you feel you have a good grasp of the basic logic and concepts of programming, learning both Python and C++ might work for you, but if you don't already have a good grasp at both procedural flow concepts and object-oriented concepts, I would probably stick with one language unless you're feeling ambitious.


> because i feel it is more detailed so i can see what is happening. now when i saw your code i got shocked

"Absorb what is useful, discard what is useless, and add what is specifically your own." - Bruce Lee

Yes, newer versions of C++ (C++11 and C++20 in particular) were major overhauls of the language, but backwards compatibility was kept in 99% of cases. People will have different opinions about "the way" to write C++; try out different things to see what you like, but don't take any one advice too dogmatically, including this advice :) Part of the "issue" with C++ is that there's 7 different ways to do basic things like variable initialization because of all the history behind the language.

Also note that https://en.cppreference.com/ is meant more as a reference site (which it does a really good job at!), but less as a tutorial itself.
Last edited on
well noted @Ganado, i really appreciate it,
>I'm not sure where you are at as far as your own personal development

i'm still in the beginning as you see, i think sorting array should be well known for any beginner, actually i saw a python function sorts the list automatically, but i was curious to know how this function was coded, i tried to code it in python but didn't give me the desired results so i wrote it in C++ because i didn't know how to write 2 loops related to each other in python, i kept try and error in c++ till i reached to this relation y = x+1 , it was difficult to me to write it in python because the loop is not detailed like c++ but finally i got it like this in python:
1
2
3
4
5
for x in range(len(nums)):
     for y in range(x,len(nums)-1): # x+1 didn't work here like c++!!
         if nums[y+1] < nums[x]:
            nums[x], nums[y+1] = nums[y+1], nums[x]
print(nums) 

i got the desired results but that was because of c++ detailed loop not the new C++ style it is similar to python hhhhhh
anyway, thanks a lot for your help and sorry for the long reply but i'm happy that i found someone to help and hear me :)
it was nice to talk to you guys
best regards and keep in touch :)
Last edited on
I can't comment on Python as I don't use it. However if you're learning C++ then I suggest you work though the tutorial from the link I gave above:
https://www.learncpp.com/

+1 for learncpp.com

semsemdiver, now you have me curious, what do you mean by "x+1 didn't work here like C++"?
for y in range(x,len(nums)-1): # x+1 didn't work here like c++!!

Can you show the Python code that "didn't work"? It should have been almost 1:1 the same logic as the C++ code.
Last edited on
Registered users can post here. Sign in or register to post.