Example 1: C++ sorting array
using namespace std;
int main()
{
//array declaration
int arr[MAX];
int n,i,j;
int temp;
//read total number of elements to read
cout<<"Enter total number of elements to read: ";
cin>>n;
//check bound
if(n<0 || n>MAX)
{
cout<<"Input valid range!!!"<<endl;
return -1;
}
//read n elements
for(i=0;i<n;i++)
{
cout<<"Enter element ["<<i+1<<"] ";
cin>>arr[i];
}
//print input elements
cout<<"Unsorted Array elements:"<<endl;
for(i=0;i<n;i++)
cout<<arr[i]<<"\t";
cout<<endl;
//sorting - ASCENDING ORDER
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(arr[i]>arr[j])
{
temp =arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
//print sorted array elements
cout<<"Sorted (Ascending Order) Array elements:"<<endl;
for(i=0;i<n;i++)
cout<<arr[i]<<"\t";
cout<<endl;
return 0;
}
Example 2: sort c++
int myints[] = {32,71,12,45,26,80,53,33};
// using default comparison (operator <):
std::sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33
// fun returns some form of a<b
std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)
Example 3: sorting algorithm c++
using namespace std;
int main(int argc, char const *argv[])
{
int numb[7];
int i, j;
for(i=0;i<=6;i++)
{
cout << "Enter a number" << endl;
cin >> numb[i];
}
for (i=0;i<=5;i++)
{
for (j=i+1;j<=5;j++)
{
int temp;
if (numb[i] > numb[j])
{
temp = numb[i];
numb[i] = numb[j];
numb[j] = temp;
}
}
}
for (i=0;i<=6;i++)
{
cout << endl << numb[i] << endl;
}
}
Example 4: sort inbuilt function in c++
using namespace std;
int main(){
int a[5] = {5, 2, 6,3 ,5};
int n = size(a);
sort((a), a + n);
for(int i = 0; i < n; i++){
cout << a[i];
}
return 0;
}
Example 5: sort c++
// sort algorithm example
bool myfunction (int i,int j) { return (i<j); }
struct myclass {
bool operator() (int i,int j) { return (i<j);}
} myobject;
int main () {
int myints[] = {32,71,12,45,26,80,53,33};
std::vector<int> myvector (myints, myints+8); // 32 71 12 45 26 80 53 33
// using default comparison (operator <):
std::sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33
// using function as comp
std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)
// using object as comp
std::sort (myvector.begin(), myvector.end(), myobject); //(12 26 32 33 45 53 71 80)
// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}