# Outputting an Array of 5 Numbers in Order

• 06-30-2009
bengreenwood
Outputting an Array of 5 Numbers in Order
Hi,

Simple question. Say you want to output an array of 5 numbers in order, with the highest first. Would the following be an efficient way to do it, or are there ways to do this better?

Thanks.

Code:

```#include <iostream> using namespace std; int main() {     int tempscore, b;     int tempscore2 = 999;     int a = 0;     int scores[5] = {33, 99, 74, 89, 12};     while (a < 5)     {         tempscore = -999;         for (b = 0; b < 5; b++)             if ((scores[b] > tempscore) && (scores[b] < tempscore2))                 tempscore = scores[b];         for (b = 0; b < 5; b++)             if (scores[b] == tempscore)             {                 cout << scores[b] << " ";                 a++;             }         tempscore2 = tempscore;     } }```
• 06-30-2009
laserlight
Quote:

Originally Posted by bengreenwood
Simple question. Say you want to output an array of 5 numbers in order, with the highest first. Would the following be an efficient way to do it, or are there ways to do this better?

For an array of just 5 numbers it does not really matter, but it would probably be both more efficient and clearer to sort the array first then print in the sorted order. For example:
Code:

```#include <cstddef> #include <algorithm> #include <functional> #include <iterator> #include <iostream> int main() {     using namespace std;     int scores[] = {33, 99, 74, 89, 12};     const size_t size = sizeof(scores) / sizeof(scores[0]);     // Sort in descending order.     sort(scores, scores + size, greater<int>());     // Print in the sorted order.     copy(scores, scores + size, ostream_iterator<int>(cout, " ")); }```
You could of course implement your own sort function if you need to, and use a simple loop to print instead of using std::copy.
• 06-30-2009
grumpy
Depends what you mean by "efficient" and "better". There are many measures (eg memory usage, speed, minimum lines of code, likelihood of working for all possible data in the array) you could use to define those terms.

An alternative to your code is this;
Code:

```#include <algorithm> #include <iostream> #include <ostream> #include<functional> int main() {   int scores[5] = {33, 99, 74, 89, 12};   std::sort(scores, scores + 5, greater<int>());   std::copy(scores, scores + 5, std::ostream_iterator<int>(std::cout, " "));   return 0; }```
I make no particular claims of efficiency or goodness, but - unlike your code which assumes values between -999 and 999 - this will work for all possible values in the scores array.