Sorting an array in a non-ascending order

I wrote a program which generates random numbers between -10 and 100, now I need that sorted.

To generate the numbers I used an array, now I don't know where should I go. I also tried putting what it contains into a vector and then outputting the vector, though it does not seem to work.
Without showing us some code it's impossible to say what you did wrong.
I also tried putting what it contains into a vector

So call sort on the vector.
http://www.cplusplus.com/reference/algorithm/sort/
If you want the result in descending order, just change the comparison function.

then outputting the vector, though it does not seem to work.

Without seeing your code, we can't tell you what's wrong.
Try to use this code: Insertion sort

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
#include <iostream>
using namespace std;

void change(int& i, int& i2){
    int aux;
    aux = i;
    i = i2;
    i2 = aux;
}
int main(){
    int size;
    cin >> size;
    int arr[size];
    for (int i = 0; i < size; i++){
        cin >> arr[i];
    }
    for (int i = 0; i < size; i++){
        int smaller = i;
        for (int j = i+1; j < size; ++j){
            if(arr[i]<arr[j]){
                smaller=j;
                }
        }
        change(arr[i], arr[smaller]);
    }
    for (int i = 0; i < size; i++){
        cout << arr[i] << ' ';
    }
    return 0;
}
Here is a very old sort I had, its N(x+1)/(x) run time profile. Its called shell sort. You can define stype as double or int or some class that can behave like a double or int. Its mostly obsolete with vector - sort, but its still very very good. As with the others, change the conditions and swapping to reverse the order, but unlike the others, you can hack the harr array to modify behavior as well, take out the 1 and it will be nearly sorted but not entirely,and the more numbers you take out, the more randomized it will get while still being generally ascending.

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

const int harr[] = 
{ 
0, /*terminal condition for sort	*/ 
1, 3,7,
10,
53,
105,
542,
1047,
6239, 
16256,
56720,
134096,
579823,
1000021,
5430201,
999999999 /*terminal condition for find index	*/
};	


void ssort(stype *list , const int size);
void ssort(stype *list , const int size)
{	
int i;
int j, dx = 1;	

while(size > harr[dx])
{
  dx++; /*get index in sequence, +1 */
}

while(--dx)	
{
  const int hdx = harr[dx]; //this guy is important!
  for(i = hdx; i < size; i++)	
  {
   const stype temp = list[i]; 
   for(j = i; (j >= hdx) && (list[j-hdx] > temp); j -= hdx) 
    {
       list[j] = list[j-hdx];	
    } 
    list[j] = temp; 
   }	
 } 
}
Last edited on
This is what I came up with after making it more clear.
Can someone explain why is that code not working 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
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <vector>
#include <algorithm>
#include <ctime>

using namespace std;
int main()
{
    vector<int> arraysorted;
    srand(time(NULL));

    const unsigned int sizeOfArray = 10;
    int numberArray[sizeOfArray];

    for (int i = 0; i < sizeOfArray; i++)
    {
        numberArray[i] = -10+(rand()) % 100;
        cout<<numberArray[i]<<endl;
        arraysorted.insert(numberArray[i]);
        sort(arraysorted.end(), arraysorted.begin());
        for( int z = 0; z < arraysorted.size(); z++)
        {
            printf("%9d\n", arraysorted[z]);
        }
    }


return 0;
}
Last edited on
Just in case you chose to follow AbstractionAnon’s suggestion:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <algorithm>
#include <iostream>

void waitForEnter();

int main()
{
    int arr[] { 54, 708, 702, 235, 302, 737, 259, 10, 710, 578 };
    std::sort(arr, &arr[sizeof(arr)/sizeof(arr[0])]);
    std::reverse(arr, &arr[sizeof(arr)/sizeof(arr[0])]);
    for(const auto e : arr) { std::cout << e << ' '; }
    std::cout << '\n';
    waitForEnter();
    return 0;
}

void waitForEnter()
{
    std::cout << "\nPress ENTER to continue...\n";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

Last edited on
Line 21: insert needs at least two parameters - see http://www.cplusplus.com/reference/vector/vector/insert/

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
#include <algorithm>
#include <ctime>
#include <iostream>
#include <vector>

constexpr int ARR_SIZE = 10;
void waitForEnter();

int main()
{
    int numberArray[ARR_SIZE];
    std::vector<int> arraysorted(ARR_SIZE);
    srand(time(NULL));

    for (int i = 0; i < ARR_SIZE; i++)
    {
        arraysorted.at(i) = numberArray[i] = -10 + (rand()) % 100;
    }
    for(const auto e : arraysorted) { std::cout << e << ' '; }
    std::cout << '\n';
    sort(arraysorted.rbegin(), arraysorted.rend());
    for(const auto e : arraysorted) { std::cout << e << ' '; }
    std::cout << '\n';
    waitForEnter();
    return 0;
}

void waitForEnter()
{
    std::cout << "\nPress ENTER to continue...\n";
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

I tried using push_back instead and it still refuses to run, I don't know why.


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
#include <iostream>
#include <cstdio>
#include <conio.h>
#include <vector>
#include <algorithm>
#include <ctime>

using namespace std;
int main()
{
    vector<int> arraysorted;

    srand(time(NULL));

    const unsigned int sizeOfArray = 10;
    int numberArray[sizeOfArray];

    for (int i = 0; i < sizeOfArray; i++)
    {
        numberArray[i] = -10+(rand()) % 100;
        arraysorted.push_back(numberArray[i]);
        sort(arraysorted.end(), arraysorted.begin());
        for(int z = 0; z < arraysorted.size(); z++)
        {
            printf("%9d\n", arraysorted[z]);
        }
        cout<<numberArray[i]<<endl;
    }

return 0;
}
In Visual Studio 2015 I got the following error: Expression: invalid iterator range
Have a closer look at line 22
Why are you mixing C-stdio and C++ streams?

Why are you trying to "sort" your array before the array is completely populated?

Why do you have end() and begin() reversed in your sort call?

Why do you have both the vector and array? I suggest you stick with the vector.

Something more like:

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
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    vector<int> arraysorted;
  
    for (int i = 0; i < 10; i++)
    {
        arraysorted.push_back(-10 + (rand()) % 100);
    }
    
    for(auto& itr : arraysorted)
        std::cout<< itr << ' ';
    std::cout << std::endl;
    
    sort(arraysorted.rbegin(), arraysorted.rend());

    for(auto& itr : arraysorted)
        std::cout<< itr << ' ';
    std::cout << std::endl;

    return 0;
}

The above should sort the vector in descending order (note the use of the reverse iterators).

Last edited on
Well, now it makes sense.

I had no idea I must use rbegin and rend instead of simply swapping the sides and I could put the whole random number generator in a push_back.

Thank you!

If you don't mind me asking, I never seem to be getting the '100' output. Is my command wrong? I've heard somewhere that it should be something like +1 at the end but I'm not sure.
Well really I would recommend you consider using the C++ random class instead. But to answer your question with a question: Did you find and study any documentation for this standard C function? Here is one such link: http://www.cplusplus.com/reference/cstdlib/rand/

Glad you brought it up (that link above).

Is it better to use rand() % 100 - 10 or -10+(rand()) % 101 or does not matter?
Last edited on
Is it better to use rand() % 100 - 10 or -10+(rand()) % 101 or does not matter?

What exactly are you trying to get from the random number generator? And yes the how matters.

And by the way I removed the call to srand() so that the same sequence of numbers are provided to make troubleshooting easier. If you want different sequences you'll need to reintroduce the srand() call with the proper seed value.

Glad you brought it up.

What did I bring up?
Last edited on
I already introduced the srand(time(NULL)).
What I'm trying to achieve is to generate numbers between [-10, 100]. Apparently, the bigger the number the smaller chance it has to get selected, though I never saw 100 outputted by my code.

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
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <ctime>

using namespace std;
int main()
{


    cout<<"10 random numbers within the range of [-10, 100] sorted in a descending order: "<<endl;
vector<int> arraysorted;
srand(time(NULL));
for(int i = 0; i < 10; i++ )
{
    arraysorted.push_back(-10+(rand()) % 101);
}
sort(arraysorted.rbegin(), arraysorted.rend());
for(int z = 0; z < arraysorted.size(); z++)
{
    printf("%9d\n", arraysorted[z]);
}

return 0;

}
What I'm trying to achieve is to generate numbers between [-10, 100].

Well your code will never produce 100, in fact the highest number it will produce is 90.

So it seems like you didn't throughly study the documentation supplied or perhaps you mis-read the documentation?
A typical way to generate trivial pseudo-random numbers in a determined range using rand is to use the modulo of the returned value by the range span and add the initial value of the range:

Since you desire a range span from -10 to 100 that includes both the -10 and the 100 your range span is 111 (10 + 100 + 1). So your formula should be rand() % 111 - 10.




Why are you using C-stdio functions instead of C++ streams?

Thank you, now it runs as intended.

As to the functions, is it bad that I use them?
Are you learning C or C++? The C++ streams are much safer than the C-stdio functions so if you want to learn C++ then you should be learning the C++ streams, use C-stdio functions if you want to learn C. And remember that the C-stdio functions don't know what to do with C++ classes like std::string and others.






Topic archived. No new replies allowed.