简体   繁体   中英

Insertion sort using a list STL recursively

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;
}
}

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;
            }
        }
    }
}

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