Hi friends,
I am trying to sort the values in one array based on the sorting sequence of another array. I use sort(A) for sorting A.
For ex,
A=[9,6,3,5,7];
B=[1,2,3,4,5];
Sorted values of A : [3,5,6,7,9]
B sorted w.r.t A : [3,4,2,5,1]
My code is as follows. I am not able to figure out how to use the sort command to get the sorting done.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int main(){
vector <int> A(5),B(5);
for (int d=0;d<5;d++){
A[d]=rand()%10;
B[d]=d;
}
sort(B.begin(),B.end(),sort_vector());// What should be the sort_vector()
// so as to sort the values of B[]
// based on the sorted order of A[]?
getchar();
return 0;
}
I dont understand yet... if A and B are vector<ints> will it still work?
Also, I am not able to understand the logic...
My problem was to be able to sort an array, and obtain the sorted array of indices too.
Is there an easier way to do it?
#include<iostream>
usingnamespace std;
int main() {
int array[5] = {3, 4, 6, 7, 1}; //original 5 element array that needs sorting
int newarray[5]; //new sorted array that will be constructed based on old array
// \/ Finds the maximum number of the array and sets the first element of the new array = to the max
int firstmax = array[0];
int secondmax = 0;
for (int i = 0; i < 5; i++) {
secondmax = array[i];
if (secondmax > firstmax) {
firstmax = secondmax;}}
newarray[0] = firstmax;
// /\ Finds the maximum number of the array and sets the first element of the new array = to the max
// \/ Sorts remaining elements of the array in descending order
int positron = 1;
int difference = 1;
int counter = 0;
while (true) {
for (int i = 0; i < 5; i++) {
if (array[i] == firstmax - difference) {
newarray[positron] = firstmax - difference;
firstmax -= difference;
difference = 0;
positron++;
counter++;}}
difference++;
if (counter == 4) {break;}}
// /\ Sorts remaining elements of the array in descending order
// \/ Prints the array
for (int i = 0; i < 5; i++) {
cout << newarray[i];}
// /\ Prints the array
while (true) {}
return 0;}