sort the array in ascending order c++ code example
Example 1: c++ how to sort numbers in ascending order
int arr[] = { 9, 8 , 3 , 5, 1, 2 , 0 , 4, 10,6 };
for (int i = 0; i < 10; i++)
{
for (int j = i + 1; j < 10; j++)
{
if (arr[i] > arr[j])
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for (int i = 0; i < 10; i++)
{
cout << arr[i] << endl;
}
Example 2: how to arrange array in ascending order in c++\
#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;
}