In: Computer Science
Use C language , pointer
limit use
//#include <stdio.h>
//#include <stdlib.h>
//#include <time.h>
For example,
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]
#include <stdio.h>
void sort(int n, int* ptr)
{
int i, j, k;
// sorting the numbers using pointer
references
for (i = 0; i < n; i++) {
for (j = i + 1; j <
n; j++) {
if (*(ptr + j) < *(ptr + i)) {
k = *(ptr + i);
*(ptr + i) = *(ptr + j);
*(ptr + j) = k;
}
}
}
int main()
{
int n, i,j,arr[], copy[];
printf("Enter the required size of the
array");//taking the size as input
scanf("%d", &n);
printf("Enter the elements of the
array");
for(i=0; i<n; i++)
{
printf("Enter the %dth element of the
array: ", i);
scanf("%d", &arr[i]);
}
arr= new int[n];
copy= new int [n];//copy[] is of the same size
as arr[] and holds the elements of arr[] in the same order
for(i=0; i<n; i++)
{
copy[i]= arr[i];
}
sort(n, arr); //calling sort() to sort using
pointers
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
if(arr[i]==copy[j])//matching the
elements of the sorted array with the unsorted one
printf("%d",
j);//the original indices of the sorted elements
}
}
return 0;
}