Sorting an array based on a different arrays values

Basically i have to do what it says in the title.for example if
arr1 = {18,19,4,11}
arr2 = {1,2,3,4}
after sorting
arr2 = {2,1,4,3}
Basically i have to sort arr2 in descending order based on arr1.
Ive tried doing it with the bubble sort method but something keeps going wrong. Here is my code
for(i = 0; i < k; i++)
{
for(j = 0; j < k+1; j++)
{
if(arr1[i] < arr1[j])
{
temp = arr2[i];
arr2[i] = arr2[j];
arr2[j] = temp;
}
}
}
It is totally unclear what you are trying to accomplish.
Shouldn't it be {3,4,1,2} after sorting? That's the only way it could make sense.
EDIT: Nevermind, you wanted descending order, of course...whoops.

Basically, whatever changes to make to array 1, also make to array 2. You can't only change array 2, you have to change array 1 at the same time.
Last edited on
im trying to get the elements in arr2 to show how large the corresponding element in arr1 is with 1 being the largest and 5 being the smallest
Yes, and I just explained. In your code you are only changing arr2, but arr1 stays the same, so...it doesn't sort correctly, it just goes back and forth on each pass.
Like this?
for(i = 0; i < k; i++)
{
for(j = 0; j < k+1; j++)
{
if(arr1[i] < arr1[j])
{
temp = arr2[i];
arr2[i] = arr2[j];
arr2[j] = temp;
temp = arr1[i];
arr1[i] = arr1[j];
arr1[j] = temp;
}
}
}
That looks right to me. Go ahead and test it!
Also, please use code tags next time you post some code. Thanks !
Thank you so much for the help
Topic archived. No new replies allowed.