In: Computer Science
Use C language.
I have random array [4,2,7,1,9,8,0].
Sort the array's index but cannot change the position of item in the array, if you copy the array to a new array, you also cannot change the item's position in array.
The index now is[0,1,2,3,4,5,6]
The output should be[6,3,1,0,2,5,4]
Code:
#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,j,a[10],helper(int [],int);
clrscr();
printf("enter the number of elements:");
scanf("%d",&n);
printf("enter the elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
helper(a,n);
getch();
}
int helper(int a[],int n)
{
int b[10],c[10],i,j,temp,ele;
for(i=0;i<n;i++)
{
b[i]=a[i];
}
for(i=n-1;i>=0;i--)
{
for(j=0;j<i;j++)
{
if(b[j]>b[j+1])
{
temp=b[j];
b[j]=b[j+1];
b[j+1]=temp;
}
}
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
ele=b[i];
if(ele==a[j])
{
c[i]=j;
}
}
}
printf("Indexes are:");
for(i=0;i<n;i++)
{
b[i]=a[i];
printf("%d,",c[i]);
}
}
Reference:
Output: