Insertion sort using a list STL recursively

2019-08-09 15:24发布

So I am trying to modify this code of vectors into lists. I understand vectors but fairly new to lists. This is what I have tried so Far how can I fix this Please let me Know. Here is the original vector code:

void insertion_sort(std::vector <int> &num) {
int i, j, key;
bool insertionNeeded = false;

for (j = 1; j < num.size(); j++) {
    key = num[j];
    insertionNeeded = false;
    for (i = j - 1; i >= 0; i--) { // larger values move right

        if (key < num[i]) {
            num[i + 1] = num[i];
            insertionNeeded = true;
        }
        else
            break;
    }
    if (insertionNeeded)
        num[i + 1] = key;    //Put key into its proper location
}
}

Here is the code I tried to convert to Lists: I am getting an error when I run it

void insertion_sort(list<int> &li) {
int i, j, key;
bool insertionNeeded = false;
list<int>::iterator itr = li.begin();
for (j = 1; j < li.size(); j++) {
    advance(itr, j);
    key = *itr;
    insertionNeeded = false;
    for (i = j - 1; i >= 0; i--) { // larger values move right
        advance(itr, i);

        if (key < i) {
            advance(itr, i + 1);
            int temp1 = *itr;
                 advance(itr, i);
                 int temp2 = *itr;

                 temp1 = temp2;
            insertionNeeded = true;
        }
        else
            break;
    }
    if (insertionNeeded)
        advance(itr, i + 1);
        *itr = key;
}
}

1条回答
爷、活的狠高调
2楼-- · 2019-08-09 15:46

This is my quick answer. The test code is here.

Note that std::advance modifies its argument. OTOH, std::next leaves its argument unmodified.

void insertion_sort(std::list<int> &li)
{
    for (auto j = 1U; j < li.size(); ++j) 
    {
        auto itr = li.begin();
        std::advance(itr, j);
        const auto key = *itr;

        for (auto i = j; i > 0U; --i) // i is just a counter.
        {        
            std::advance(itr, -1);

            if (key < *itr) // larger values move right
            {
                const int temp = *itr;
                *itr = key;
                *std::next(itr) = temp;        
            }
            else{            
                break;
            }
        }
    }
}
查看更多
登录 后发表回答