Using C Able Keep Track Previous Indexes Sorting Vector Used Pair Vector However Approach Q43817868
Using c++, I was able to keep track of previous indexes aftersorting a vector. I used pair vector. However, my approach used thestd::sort() already present in c++. My program works with sort(),but I also want to use bubble sort with it. I thought that workingon arr[].first would sort the values in the first pair and leavethe second part of the pair alone, but no. When sorting arr.first,arr.second get also sorted. Below you can see what I tried. Isthere a way I can still sort the values, and keep their originalindexes using bubble sort? I would like to emphasize that Ireally want to work with the bubble sort I have, notsort().
—————————————————————
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 <iostream>
#include <vector>
#include <limits>
#include <algorithm>
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<pair<int, int> > 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 << ” “; }
}
Expert Answer
Answer to Using c++, I was able to keep track of previous indexes after sorting a vector. I used pair vector. However, my approach…
OR