Bucket Sort on vector of positive integers - C++ STL

C++ examples for STL:vector

Description

Bucket Sort on vector of positive integers

Demo Code

#include <algorithm>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
class BucketSort {
 public:/*from  w w  w. j av  a 2 s  .  c o  m*/
    void sort(std::vector<int>&);

    // print a vector
    template <typename T>
    void printVector(const std::vector<T>& data) {
        for (T elem : data) std::cout << elem << " ";

        std::cout << std::endl;
    }

 private:
};

void BucketSort::sort(std::vector<int>& intVec) {
    std::vector<int> bucket;

    // assign values to bucket
    for (int elem : intVec) bucket.push_back(elem);

    // sort individual buckets
    std::sort(bucket.begin(), bucket.end());

    // reassign to original vector
    intVec.clear();

    for (int value : bucket) intVec.push_back(value);
}

int main(int argc, const char* argv[]) {
    std::srand(time(0));

    const size_t limit = 100;
    const size_t size = 20;
    std::vector<int> intVec;

    for (size_t i = 0; i < size; ++i) intVec.push_back(((rand() % limit) + 1));

    BucketSort bs;

    std::cout << "\nUnsorted Vector:" << std::endl;
    bs.printVector(intVec);

    std::cout << std::endl;

    bs.sort(intVec);

    std::cout << "\nSorted Vector:" << std::endl;
    bs.printVector(intVec);

    return 0;
}

Result


Related Tutorials