Question: Using c++, I was able to keep track of previous indexes after sorting a vector. I used pair vector. However, my approach used the std::sort()

Using c++, I was able to keep track of previous indexes after sorting a vector. I used pair vector. However, my approach used the std::sort() already present in c++. My program works with sort(), but I also want to use bubble sort with it. I thought that working on arr[].first would sort the values in the first pair and leave the second part of the pair alone, but no. When sorting arr.first, arr.second get also sorted. Below you can see what I tried. Is there a way I can still sort the values, and keep their original indexes using bubble sort? I would like to emphasize that I really want to work with the bubble sort I have, not sort().

---------------------------------------------------------------

input data:

4

50 98 17 79

answer:

3 1 4 2

---------------------------------------------------------------

---------------------------------------------------------------

But using my solution with bubble sort, I get:

1 2 3 4

which is not the desired answer.

---------------------------------------------------------------

#include

#include

#include

#include

using namespace std;

void swap(int *max, int *last){

int temp = *last;

*last = *max;

*max = temp;

}

int main(){

int size = 0, val = 0;

int count = 0;

cin >> size;

cin.clear();

vector > arr;

while(count < size){

cin >> val;

arr.push_back(make_pair(val, count));

++count;

}

//bubble sort starts below.

for(int i = 1; i < size; ++i){

for(int j = 0; j < size - 1; ++j){

if(arr[j].first > arr[j + 1].first) {

swap(arr[j].first, arr[j+1].first); } } }

//below is the working solution

//sort(arr.begin(), arr.end());

for (int i = 0; i < arr.size(); i++){

cout << arr[i].first << " ";

}

cout << endl;

for (int ii = 0; ii < arr.size(); ii++){

cout << arr[ii].second + 1 << " "; }

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!