简体   繁体   中英

Insertion sort function acts weird C++

I want to make a function to sort random numbers (generated using another function) and I've been trying to do that for some time, but nothing worked. Now I have a problem that sometimes my program compiles without any problems and sometimes it says "vector subscript out of range" and even if it compiles properly it inserts some numbers in the wrong order (especially when the next number to sort is smaller than the previous one). I've tried to use debugger and to figure out what's wrong but for me everything seems fine. Could you be so kind and help me? Thank you very much.

std::vector <int> insertion_sort(std::vector <int> generated)
{
    using namespace std;
    bool emplaced = false;
    vector <int> buffor(1);

    buffor[0] = generated[0];

    for (int i = 1; i < generated.size(); i++)
    {
        emplaced = false;

        if (generated[i] >= buffor[i-1])
        {
            buffor.push_back(generated[i]);
        }
        else
        {
            int x = 2;
            while (((i - x) > -1))
            {
                if (emplaced == true)
                {
                    break;
                }

                if ((i - x) == 0)
                {
                    buffor.emplace(buffor.begin(), generated[i]);
                    emplaced = true;
                }

                if (generated[i] < bufor[i - x])
                {

                }
                else
                {
                    buffor.emplace(buffor.begin() + (i-x), generated[i]);
                    emplaced == true;
                }

                x++;
            }
        }

    }

    return buffor;
}

Insertion sort is a simple sorting algorithm and can be implemented by more compact and straightforward code like as follows:

DEMO is here.

std::vector<int> insertion_sort(const std::vector<int>& generated)
{
    auto shifted(generated);

    for (std::size_t j = 1; j < shifted.size(); ++j) 
    {
        const auto temp = shifted[j];

        if(shifted[j-1] > temp)
        {
            int i = j;

            do{
                shifted[i] = shifted[i-1];
                --i;
            } while(i > 0 && shifted[i-1] > temp);

            shifted[i]=temp;
        }
    }

    return shifted;    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM