C ++ sorts numbers from smallest to largest

If I have a user, enter 10 random numbers, and I want to order them from the smallest to the largest, which is the best way to do this using the simplest C ++ language.

+7
source share
6 answers
#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; } 
+13
source
 std::vector<int> numbers; // get the numbers from the user here. std::sort(numbers.begin(), numbers.end()); 
+20
source

Use a structure that supports 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"; } 

Vocation:

 $ yourprogram 1 5 4 6 7 82 6 7 8 

(Note: the number of arguments is unlimited)

+2
source

It depends on your requirements. If you just want to sort them, and the speed is only moderate, insertion sorting will be fine for such a small value of n (10). Quickly implement (from scratch) and is suitable for small sizes.

0
source
  //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; } 
0
source

You can write something yourself, but you really need to use the qsort function.

-7
source

All Articles