HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcppMinor

Vector Sort Function

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
sortfunctionvector

Problem

I had heard about sorting for a while, but never actually gave it a try. So I decided to make an algorithm that would sort the members of a vector from least to greatest. Though this may seem pretty simple and/or silly, I actually put a lot of thought into it and wrote out tables/diagrams.

#include 
#include 

namespace{
    typedef unsigned int uint;
}

std::vector sort(std::vectora)
{
    for (int i = 1; i  a[i]) std::swap(a[j], a[i]);
        }
    }

    return a;
}

int main()
{
    std::vector a = { 17, 12, 1, 20, 4, 6, 94 };

    for (uint i = 0; i < a.size(); ++i){
        std::cout << sort(a)[i] << std::endl;
    }
}


I know there's probably some sort function part of the standard C++ library, but for a sort function from scratch, how efficient is this? What could I do to improve it?

Solution

It's not ideal to call sort() for each element. The first call already gives you the sorted vector, so each additional call just needlessly overwrites it. This approach would also be very slow if the vector were much larger.

Since you're already returning a vector, you just need to sort once and then print once:

int main()
{
    std::vector a = { 17, 12, 1, 20, 4, 6, 94 };

    a = sort(a);

    for (auto& iter : a)
    {
        std::cout << iter << "\n";
    }
}


There's also no need for the typedef. To help ensure you're using the proper type, you can use auto instead. You should also replace the ints in sort() with auto. Having higher compiler warnings would've alerted you to this type mismatch.

Code Snippets

int main()
{
    std::vector<int> a = { 17, 12, 1, 20, 4, 6, 94 };

    a = sort(a);

    for (auto& iter : a)
    {
        std::cout << iter << "\n";
    }
}

Context

StackExchange Code Review Q#119064, answer score: 2

Revisions (0)

No revisions yet.