C++ sorting numbers from smallest to biggest
If I have the user enter 10 random n开发者_如何学Goumbers and I want to order them from smallest to biggest what is the best method to do this using the most basic C++ language.
std::vector<int> numbers;
// get the numbers from the user here.
std::sort(numbers.begin(), numbers.end());
#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;
}
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)
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.
//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;
}
You can write something yourself, but really should use qsort function.
精彩评论