Oliver
Oliver

Reputation: 831

C++ sorting numbers from smallest to biggest

If I have the user enter 10 random numbers and I want to order them from smallest to biggest what is the best method to do this using the most basic C++ language.

Upvotes: 9

Views: 62603

Answers (6)

Leo Ivas
Leo Ivas

Reputation: 1

    //this is sorting min--->max without pointers
    #include<iostream>
    using namespace std;
    int main()
    {int n;
    cout<<"How much numbers you wanna sort? "<<endl;
    cin>>n;
    int broj[n];
    cout<<"Enter numbers: "<<endl;
    for(int k=0;k<n;k++)
    {
    cin>>broj[k];
    }
    int min=0;
    for(int z=0;z<n;z++)
    {
    loop:
    min=broj[z];

    for(int i=z;i<n;i++)
   {
        if(min<=broj[i])
        {
        }
        else
        {
             min=broj[i];
             broj[i]=broj[z];
             broj[z]=min;
             goto loop;         
         }
   }
   }
   cout<<endl<<"--------------"<<endl;
   for(int j=0;j<n;j++)
   {
   cout<<broj[j]<<endl;
   }
   return 0;
   }

Upvotes: 0

Matthieu M.
Matthieu M.

Reputation: 299810

Use a structure that maintains ordering: std::multiset

#include <iostream>
#include <set>

#include <boost/lexical_cast.hpp>

int main(int argc, char* argv[])
{
  std::multiset<int> set;

  for (int i = 1; i != argc; ++i) {
    set.insert(boost::lexical_cast<int>(argv[i]));
  }

  for (int i: set) { std::cout << i << " "; }
  std::cout << "\n";
}

Invocation:

$ yourprogram 1 5 4 6 7 82 6 7 8

(Note: the number of arguments is not constrained)

Upvotes: 2

pyfex
pyfex

Reputation: 1205

#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

int main() {

    vector<int> vec;

    vec.push_back(1);
    vec.push_back(4);
    vec.push_back(3);
    vec.push_back(2);

    sort( vec.begin(), vec.end() );

    for (vector<int>::const_iterator it=vec.begin(); it!=vec.end(); ++it) {
      cout << *it << " ";
    }
    cout << endl;
    return 0;
}

Upvotes: 14

MM.
MM.

Reputation: 4274

It depends on your requirements. If you just want to sort them, and speed is only of moderate concern, an insertion sort would be fine for such a small n-value (10). Quick to implement (from scratch), and suitable for small set sizes.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490108

std::vector<int> numbers;

// get the numbers from the user here.    

std::sort(numbers.begin(), numbers.end());

Upvotes: 21

Oleg
Oleg

Reputation: 9

You can write something yourself, but really should use qsort function.

Upvotes: -8

Related Questions