Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort of arrays and their position

I have a sort problem.

I have two array

int a[] ={index1,index2,index3...indexI};
int b[] ={num1,num2,num3.......numI};

Array b[] is having numbers in random order but their position corresponds to position in a[]. For example num1 is the value of index1, num2 is the value of index2.

The problem is:

I need to sort the b[] elements in descending order, at the same time I need to move the a[] elements position according to the sorted order of b[].

I can sort b[] in descending order using one of the sort algorithm but I am not able handle the simultaneous move of the a[] elements according to the b[] position change. My final output I am expecting is a[] indexes arranged in descending order of their values in b[].

Please help.

Thanks

like image 496
user679460 Avatar asked Dec 12 '22 05:12

user679460


2 Answers

int a[] ={index1,index2,index3...indexI};
int b[] ={num1,num2,num3.......numI};
int c[] = {{num1, index1}, {num2, index2}...{indexI, numI}}
sort(c);
for i = 0 to c.len
  print c[i][1]

In c++ I would use a vector of pairs. In other languages you can use a structure.

like image 63
Ivaylo Strandjev Avatar answered Dec 14 '22 19:12

Ivaylo Strandjev


If I get it correcty yu want to have something like this a = [0 1 2]; b = [5 2 8] and after sorting a = [1 0 2]; b = [2 5 8].

Which ever sorting algorithm you must just remember to change index arrays when changing number's position:

eg. swapping two positions (pseudocode)

swap(i, j): // i, j - indexes
   (b[i], b[j]) = (b[j], b[i]) // swap values
   (a[i], a[j]) = (a[j], a[i]) // swap the indexes
like image 25
szymzet Avatar answered Dec 14 '22 17:12

szymzet