In: Computer Science
C++
Given 2 int arrays that are related, sort them correspondingly.
EXAMPLE:
int arr1[] = {84, 4, 30, 66, 15};
int arr2[] = {7, 5, 2, 9, 10};
SORTED ANSWER:
4 - 5
15 - 10
30 - 2
66 - 9
84 - 7
IN C++
Below is your code: -
#include<iostream>
using namespace std;
int main() {
//declaring arrays
int arr1[] = {84, 4, 30, 66, 15};
int arr2[] = {7, 5, 2, 9, 10};
//getting size of first array
int n = sizeof(arr1)/sizeof(arr1[0]);
//code to sort the arrays
//traverse first array
for(int i=0; i<n; i++)
{
//compare it with subsequent member
of first array
for(int j=i+1; j<n; j++)
{
//If array
element is unsorted
//sort first
array and swap elemnt of second array also
if(arr1[i] >
arr1[j])
{
int temp1 =arr1[i];
int temp2 =arr2[i];
arr1[i]=arr1[j];
arr2[i]=arr2[j];
arr1[j]=temp1;
arr2[j]=temp2;
}
}
}
cout<<"SORTED ANSWER: "<<endl;
//printing the array
for(int i = 0; i < n; i ++) {
cout<<arr1[i]<<" -
"<<arr2[i]<<endl;
}
return 0;
}
Output
SORTED ANSWER:
4 - 5
15 - 10
30 - 2
66 - 9
84 - 7