KEY POINTS:
1.FIND THE 1ST SMALLEST ELEMENT AND STORE IT IN A[0]
2.FIND THE SECOND SMALLEST ELEMENT AND STORE IT IN A[1]
3.REPEAT IT UNTIL EVERY ELEMENT GET SORTED ASCENDING ORDER
#include<iostream>
using namespace std;
int main()
{
int a[50],i,j,n,min,temp;
cin>>n;
for(i=0;i<n;i++)
{
cin>>a[i];
}
for(i=0;i<n;i++)
{
min=i; //index of a[i] is stored in min
for(j=i;j<n;j++)
{
if(a[min]>a[j])
{
min=j;
}
} //this loops find the smallest element index and replace the value in min
if(min!=i) //swaps the values
{
temp=a[i];
a[i]=a[min];
a[min]=temp;
}
}
for(i=0;i<n;i++)
{
cout<<a[i];
}
return 0;
}
1.FIND THE 1ST SMALLEST ELEMENT AND STORE IT IN A[0]
2.FIND THE SECOND SMALLEST ELEMENT AND STORE IT IN A[1]
3.REPEAT IT UNTIL EVERY ELEMENT GET SORTED ASCENDING ORDER
#include<iostream>
using namespace std;
int main()
{
int a[50],i,j,n,min,temp;
cin>>n;
for(i=0;i<n;i++)
{
cin>>a[i];
}
for(i=0;i<n;i++)
{
min=i; //index of a[i] is stored in min
for(j=i;j<n;j++)
{
if(a[min]>a[j])
{
min=j;
}
} //this loops find the smallest element index and replace the value in min
if(min!=i) //swaps the values
{
temp=a[i];
a[i]=a[min];
a[min]=temp;
}
}
for(i=0;i<n;i++)
{
cout<<a[i];
}
return 0;
}
No comments:
Post a Comment