Sorting vector elements in descending order

0 votes

Please tell me what I'm doing wrong. 

When I execute the code, it takes far too long to compute the result.

#include <iostream>
#include <vector>
using namespace std;

vector<int> vec;
vector<int> sort(vector<int> x) {
    vector<int> y;
    int i = 1;
    reset:for(i = 1; i <= x.size(); i++){
        for (int j = 1; j <= x.size();) {
            if (j == i) {
                j++;
            }
            else {
                if (x[i - 1] > x[j - 1]) {
                    j++;
                }
                else {
                    i++;
                    goto reset;
                }
            }
        }
        y.push_back(x[i - 1]);
        x.erase(x.begin() + i - 1);
    }
          return y;
}

int main(){
    vec.push_back(5);
    vec.push_back(9);
    vec.push_back(3);
    vec.push_back(6);
    vec.push_back(2);

    for (int i = 1; i <= vec.size(); i++) {
        cout << sort(vec)[i-1] << " ";
    }
}

I'm sorting this series of five numbers in decreasing order. 

Please assist.

My aim was to find the largest integer in the whole vector x, shift it to the vector y, and repeat the procedure.

Jul 7, 2022 in C++ by Nicholas
• 7,760 points
1,003 views

1 answer to this question.

0 votes

Because of the goto reset instruction, I believe your sort function has entered an infinite loop. 

If you wish to construct a basic bubble-sort algorithm, follow these steps:

#include <iostream>
#include <utility>
#include <vector>

void bubble_sort(std::vector<int>& v) {
    if(v.size() == 0) return; 

    for(int max = v.size(); max > 0; max--) {
        for(int i = 1; i < max; i++) {
            int& current = v[i - 1]; 
            int& next = v[i];
            if(current < next) 
                std::swap(current, next); 
        }
    }
}

This function accepts a vector and swaps any consecutive pair of items in the vector that are out of order. 

The smallest element "bubbles" to the top of the vector as a consequence. 

The process is continued until all of the pieces are in their proper place.

When we run it, we observe that it outputs the correct answer:

int main() {
    std::vector<int> test = {5, 9, 3, 6, 2}; 

    bubble_sort(test);

    for(int i : test) {
        std::cout << i << ' '; 
    }
    std::cout << '\n';
}

To make this process faster, I'm going to use std::sort.

The standard library includes a sort function that can sort almost anything. 

std::sort is extremely well implemented, more efficient than bubble sort, and quite simple to use.

By default, std::sort sorts objects in ascending order, but it's simple to alter it to work in descending order. 

There are two approaches to this. 

The first method sorts the vector using reverse iterators (which enable you to pretend the vector is in reverse order), while the second method uses std::greater, which instructs std::sort to sort items in reverse order.

// Way 1:
std::sort(test.rbegin(), test.rend()); 

// Way 2:
auto compare_func = std::greater<>(); 
std::sort(test.begin(), test.end(), compare_func); 

We can re-write the program using std::sort:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> test = {5, 9, 3, 6, 2}; 

    auto compare_function = std::greater<>(); 
    std::sort(test.begin(), test.end(), compare_function); 


    for(int i : test) {
        std::cout << i << ' '; 
    }
    std::cout << '\n';
}
answered Jul 11, 2022 by Damon
• 4,960 points

Related Questions In C++

0 votes
0 answers

Sorting a vector in descending order

Should I  utilize  std::sort(numbers.begin(), numbers.end(), std::greater<int>()); or std::sort(numbers.rbegin(), numbers.rend()); // ...READ MORE

Jul 5, 2022 in C++ by Nicholas
• 7,760 points
2,286 views
0 votes
1 answer

How do i apply lower_bound to a range of unsorted vector elements?

What's the point of sorting your array? ...READ MORE

answered Jun 15, 2022 in C++ by Damon
• 4,960 points
1,791 views
0 votes
0 answers

What is the easiest way to initialize a std::vector with hardcoded elements?

I can make an array and initialise&nb ...READ MORE

Jun 27, 2022 in C++ by Nicholas
• 7,760 points
603 views
0 votes
0 answers

How can I get the maximum or minimum value in a vector?

In C++, how can I find the greatest or minimum value in a vector? Is it correct to assume that it would be similar with an array? Do I require an iterator?  I tried max element, but I kept receiving errors. vector<int>::const_iterator it; it = max_element(cloud.begin(), cloud.end()); error: request for ...READ MORE

Jun 27, 2022 in C++ by Nicholas
• 7,760 points
589 views
0 votes
1 answer

setuptools: build shared libary from C++ code, then build Cython wrapper linked to shared libary

There is a seemingly undocumented feature of setup that ...READ MORE

answered Sep 11, 2018 in Python by Priyaj
• 58,020 points
704 views
0 votes
1 answer

setuptools: build shared libary from C++ code, then build Cython wrapper linked to shared libary

There is a seemingly undocumented feature of setup that ...READ MORE

answered Sep 21, 2018 in Python by Priyaj
• 58,020 points
2,428 views
0 votes
1 answer

How to pass large records to map/reduce tasks?

Hadoop is not designed for records about ...READ MORE

answered Sep 25, 2018 in Big Data Hadoop by Frankie
• 9,830 points
1,463 views
0 votes
1 answer

Invalid method parameters for eth_sendTransaction

params needs to be an array, try {"jsonrpc":"2.0","method":"eth_se ...READ MORE

answered Sep 28, 2018 in Blockchain by digger
• 26,740 points
1,885 views
0 votes
1 answer

Sorting a vector of custom objects

A simple example using std::sort struct MyStruct { ...READ MORE

answered Jun 1, 2022 in C++ by Damon
• 4,960 points
1,285 views
0 votes
1 answer

Lower and Upper Bound in case of Decreasing/Non-ascending vector

Both std::lower bound and std::upper bound must have an increasing (non-decreasing) order as their objective. By giving a comparator as the 4th parameter of the functions, you may modify the meaning of "growing." To work with descending vectors, use std::greater. #include<iostream> #include<vector> #include<algorithm> #include<functional> using namespace std; int main() { ...READ MORE

answered Jun 14, 2022 in C++ by Damon
• 4,960 points
1,261 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP