sort a array c++ code example
Example 1: C++ sorting array
#include <iostream>
using namespace std;
#define MAX 100
int main()
{
int arr[MAX];
int n,i,j;
int temp;
cout<<"Enter total number of elements to read: ";
cin>>n;
if(n<0 || n>MAX)
{
cout<<"Input valid range!!!"<<endl;
return -1;
}
for(i=0;i<n;i++)
{
cout<<"Enter element ["<<i+1<<"] ";
cin>>arr[i];
}
cout<<"Unsorted Array elements:"<<endl;
for(i=0;i<n;i++)
cout<<arr[i]<<"\t";
cout<<endl;
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;
}
}
}
cout<<"Sorted (Ascending Order) Array elements:"<<endl;
for(i=0;i<n;i++)
cout<<arr[i]<<"\t";
cout<<endl;
return 0;
}
Example 2: stl sort in c++
sort(arr, arr+n);
Example 3: array sort c++
#include <iostream>
2 #include <array>
3 #include <string>
4 #include <algorithm>
5
6 using namespace std;
7
8 int main(){
9 array<string, 4> colours = {"blue", "black", "red", "green"};
10 for (string colour : colours){
11 cout << colour << ' ';
12 }
13 cout << endl;
14 sort(colours.begin(), colours.end());
15 for (string colour : colours){
16 cout << colour << ' ';
17 }
18 return 0;
19 }
66
20
21