Wednesday, July 15, 2020

You are given an array A of non-negative integers of size m. Your task is to sort the array in non-decreasing order and print out the original indices of the new sorted array.

Question:

You are given an array A of non-negative integers of size m. Your task is to sort the array in non-decreasing order and print out the original indices of the new sorted array. 
 
Example: 
 
A={4,5,3,7,1} 
 
After sorting the new array becomes A={1,3,4,5,7}. 
 
The required output should be "4 2 0 1 3"    
 
INPUT : 
 
The first line of input consists of the size of the array The next line consists of the array of size m 
 
OUTPUT : 
 
Output consists of a single line of integers 
 
CONSTRAINTS: 
 
1<=m<=106 0<=A[i]<=106 
 
NOTE: The indexing of the array starts with 0. 
 
SAMPLE INPUT  
 
5 4 5 3 7 1 
 
SAMPLE OUTPUT  
 
4 2 0 1 3 
 
ANSWER:

#include <stdio.h>

int main()
{
    int n; 
        scanf("%d",&n); 
        int a[n],b[n],i,j,temp,flag=0; 
        for(i=0;i<n;i++)
       { 
            scanf("%d",&a[i]); 
            b[i]=a[i]; 
        } 
        for(i=0;i<n-1;i++)
       { 
            flag=0; 
            for(j=0;j<n-i-1;j++)
            { 
                if(b[j]>b[j+1])
                { 
                    temp=b[j]; 
                    b[j]=b[j+1]; 
                    b[j+1]=temp; 
                    flag=1; 
                } 
            } 
            if(flag==0)
           { 
                break; 
            } 
        } 

        for(i=0;i<n;i++)
       { 
            for(j=0;j<n;j++)
           { 
                if(b[i]==a[j] && a[j]!=-1)
                { 
                    printf("%d ",j); 
                    a[j]=-1; 
                    break; 
                } 
            } 
        } 

    return 0;
}


OUTPUT:

5                                                                                                          
4 5 3 7 1                                                                                                  
4 2 0 1 3  

No comments:

Post a Comment