Как пузырьковая сортировка справляется с дубликатами для связанных списков? - PullRequest
0 голосов
/ 09 апреля 2020

Я попробовал следующую реализацию для пузырьковой сортировки связанных списков.

Я исследовал 2 метода

  1. Я попытался поменять элемент узла на пузыри (не удалось)

  2. Чтобы переставить указатели узлов, используя указатели prev, current, next. (работает)

Может ли метод 1 давать сбой?

МЕТОД 1

void List::bubbleSort( bool printAtEveryIteration ) {

    // TODO: Implement bubble sort on this implementation of single linked list.
    //       Print the linked list after every pass in the outer iteration
    //       using print(false) function in List class if parameter is true.
    //       The list should be sorted in ascending order.
    ListNode* current = _head;
    ListNode* next = _head->_next;
    ListNode* print = _head;

    int temp;

    // Last i elements are already in place
    for (int i = 0; i < _n - 1; i++) {
        current = _head; // reset the head
        next = _head->_next;
        for (int j = 0; j < _n-i-1; j++) {
            if (current->_item > next->_item) { // Swap
                temp = current->_item;
                current->_item = next->_item;
                next->_item = temp;
            }
            current = current-> _next; // Shifting
            next = current -> _next;
        }

        //Printing
        if (printAtEveryIteration) {
            print = _head;
            for (int k = 0; k < _n; k++) {
                cout << print->_item;
                cout << " ";
                print = print ->_next;
            }
            cout << "\n";
        }
    }
}

...