☞ Read an array with positive integer elements and perform sorting operation.
4
1 2 2 4
Sample Output1
0
Sample Input2
5
1 10 3 4 3
Sample Output2
1
Program
#include<stdio.h>
int main(){
int a[10],i,j,n,min_index,noOfSwaps=0,temp;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++){
min_index = i;
for(j=i+1;j<n;j++)
if (a[j]<=a[min_index])
min_index=j;
if(min_index!=i && a[min_index]!=a[i]){
temp=a[min_index];
a[min_index]=a[i];
a[i]=temp;
noOfSwaps++;
}
}
if(noOfSwaps==0)
printf("0");
else if(noOfSwaps>1)
printf("-1");
else if(noOfSwaps==1)
printf("1");
}
Test Program
- If the array is sorted with more than one swap, print -1.
- If the array is already in sorted, print 0.
- If the array is sorted with one swap, print 1.
4
1 2 2 4
Sample Output1
0
Sample Input2
5
1 10 3 4 3
Sample Output2
1
Program
#include<stdio.h>
int main(){
int a[10],i,j,n,min_index,noOfSwaps=0,temp;
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++){
min_index = i;
for(j=i+1;j<n;j++)
if (a[j]<=a[min_index])
min_index=j;
if(min_index!=i && a[min_index]!=a[i]){
temp=a[min_index];
a[min_index]=a[i];
a[i]=temp;
noOfSwaps++;
}
}
if(noOfSwaps==0)
printf("0");
else if(noOfSwaps>1)
printf("-1");
else if(noOfSwaps==1)
printf("1");
}
Test Program