#insertion sort

8 messages · Page 1 of 1 (latest)

marsh heart
#
void insertion_sort(std::vector<int> &vec) {

    int i{0}, j{0};

    for (i = 1; i < vec.size(); i++) {
        auto at_begin = i;
        for (j = i - 1; j >= 0; j--) {
            if (vec[i] < vec[j]) {
                std::swap(vec[i--], vec[j]);
            }
        }
        i = at_begin;
    }
}
``` is this code correct?
ionic plinthBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

marsh heart
#

if it is

void shell_sort(std::vector<int> &vec) {
    for (int gap = vec.size() / 2; gap > 0; gap /= 2) {

        for (int i = gap; i < vec.size(); i++) {
            auto at_begin = i;
            for (int j = i - 1; j >= gap; j--) {
                if (vec[i] < vec[j]) {
                    std::swap(vec[i--], vec[j]);
                }
            }
            i = at_begin;
        }
    }
}

why does this shell sort function doesnt sort the first element but sorts other
1 -1 -1 1 3 4 15 20 39
from
std::vector<int> a{1,-1, 20, 15, 3, 4, 1, -1, 39};

plucky lantern
#

Make some test cases

ionic plinthBOT
# plucky lantern !debugger

@marsh heart
Have you tried stepping through your code line by line in a debugger?

If you don't know how to use a debugger or don't have one set up, we highly recommend taking the time to do so.
Debuggers are immensely helpful tools for figuring out where problems emerge in code and especially when you're first learning it can help you build intuition and understanding for reasoning through code.

Resources: