In this program, the user is asked to enter 10 elements in an array. Then we perform a sort on the given array. First we check for 1st element is greater than 2nd element, if so then we swap (exchange) both elements. Then we check for 2nd and 3rd elements for greater than and so on. This technique is called as "Bubble Sort". Finally, we display the sorted array. By default here we sort the array in Ascending order, if you want to sort in descending order then you have to change the condition likeif(a[j] < a[j+1])
#include <iostream>
using namespace std;
int main( )
{
int a[10], i, j, temp;
cout<<"Enter 10 array elements\n";
for (i = 0; i < 10; i++)
{
cin>>a[i];
}
cout<<"Array elements are..\n";
for(i = 0; i< 10; i++)
{
cout<<a[i]<<" ";
}
/* Sorting logic starts here */
for(i = 0; i < 10; i++)
{
for(j = 0; j < 9; j++)
{
if(a[j] > a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
cout<<"\n\nArray elements in Ascending order are..\n";
for(i = 0; i< 10; i++)
{
cout<<a[i] << " ";
}
return 0;
}
Enter 10 array elements
32 14 20 45 2 66 47 23 30 94
Array elements are..
32 14 20 45 2 66 47 23 30 94
Array elements in Ascending order are..
2 14 20 23 30 32 45 47 66 94