Generating Random Number + Sorting

Hi,

The below code compiles correctly to generate 100 random numbers, and then sorts them, first high to low, and then reverses this.

While the program works, I'm wondering if this is the most efficient way to do such a program or technically correct method?

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <string>

using namespace std;

int main()
{
	int unsorted[100];  
	
    
	for(int i = 0; i < 100; i++)
      
	unsorted[i] = rand() % 100 + 1;
	    
	cout << "Here are the unsorted numbers: " << endl;
	
    for(int i = 0; i < 100; i++) 
	
    cout << unsorted[i] << " ";

    cout << "\n";
	
    int sorted[100];
	
    
	for(int i = 0; i < 100; i++)
    {
      int hi = -1;
      int hiIndex = -1;
      for(int j = 0; j < 100; j++)
      {
        if(unsorted[j] > hi)
        {
          hi = unsorted[j];
          hiIndex = j;
        }
      }
      sorted[i] = hi;
      unsorted[hiIndex] = -1;
    }

	cout << "\n\nHere are the sorted numbers: " << endl;
 
    for(int i = 0; i < 100; i++) 
	
	cout << sorted[i] << " ";
	
	cout << "\n";


cout << "\n\nReverse the sorted numbers: " << endl;
int sorted_reverse[100];

	for (int i = 0; i < 100; i++)
{
	sorted_reverse[i] = sorted[100 - 1 - i];
}

// print descending array 
for (int i = 0; i < 100; i++)
{
	if (i < 100 - 1)
	{
		cout << sorted_reverse[i] << " ";
	}
	
		else 
		{
			cout << sorted_reverse[i];
		}
}

cin.ignore();

	return 0;

}
if this is the most efficient way to do such a program or technically correct method?
It is uneffective (mostly because of sorting complexity) hard to read code. Consider using standard library and extracting common parts (as printing array) to the own functions. Also you do not need 3 separate arrays in your 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
29
30
31
32
33
34
35
#include <algorithm>
#include <ctime>
#include <iostream>
#include <random>
#include <vector>

int rand_int(int low, int high)
{
    static std::mt19937 rng(std::time(nullptr));
    return std::uniform_int_distribution<>(low, high)(rng);
}

template <typename C>
void print(const C& container)
{
    for(const auto& val: container)
        std::cout << val << ' ';
    std::cout << '\n';
}

int main()
{
    std::vector<int> numbers(100);
    std::generate(numbers.begin(), numbers.end(), [](){ return rand_int(1, 100); });
    std::cout << "Here are the unsorted numbers:\n";
    print(numbers);

    std::sort(numbers.begin(), numbers.end());
    std::cout << "\nHere are the sorted numbers:\n";
    print(numbers);

    std::cout << "\nReverse the sorted numbers:\n";
    std::reverse(numbers.begin(), numbers.end());
    print(numbers);
}

Topic archived. No new replies allowed.