c++ sorted array code example
Example 1: stl for sorting IN C++
// STL IN C++ FOR SORING
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main()
{
int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
int n = sizeof(arr)/sizeof(arr[0]);
sort(arr, arr+n); // ASCENDING SORT
reverse(arr,arr+n); //REVERESE ARRAY
sort(arr, arr + n, greater<int>());// DESCENDING SORT
}
Example 2: C++ sorting array
#include <iostream>
using namespace std;
#define MAX 100
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 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 /*
22 Output:
23 blue black red green
24 black blue green red
25 */