合并排序链表算法c ++

时间:2017-07-09 06:17:40

标签: c++ algorithm sorting

我还是年轻的C ++并且在算法代码方面遇到了一些麻烦,目的是对链表进行合并排序,并在每个循环中递归删除最大值元素(六个元素的数据因此需要六次打印出来动作)。我试图使用两个函数(void show和void deleteLargest)来完成我的工作。但多次尝试后无法通过。我在哪里遇到以下代码?

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <string>
#include <conio.h>
#define S 8

using namespace std;

int main()
{
    int age[S];
    int next[S];
    void show(int *age, int *next);
    void deleteLargest(int *next);

    age[1] = 9;
    age[2] = 12;
    age[3] = 7;
    age[4] = 15;
    age[5] = 8;
    age[6] = 11;

    next[0] = 3;
    next[1] = 6;
    next[2] = 4;
    next[3] = 5;
    next[4] = -1;
    next[5] = 1;
    next[6] = 2;

    show(age, next);
    deleteLargest(next);
    show(age, next);
    deleteLargest(next);
    show(age, next);
    deleteLargest(next);
    show(age, next);
    deleteLargest(next);
    show(age, next);
    deleteLargest(next);
    show(age, next);


    system("PAUSE");
    return EXIT_SUCCESS;

    _getch();
    return 0;
}

我的主要问题是可能同时使用show和deleteLargest函数的以下函数,但是虽然它失败了但没有通过show函数。主要目标是在每个步骤中按升序列出主要元素(年龄),同时删除每个循环中的最大值,直到只剩下一个元素(在这种情况下,年龄值为7)。

void show(int *age, int *next) {  // print the results
    cout << endl;
    cout << "Show effect of the action taken:\n " << endl;
    if (next[0] != 6) {
        cout << age[next[0]] << endl;
        for (int i = 0, nextIndex = next[0]; i < S - 1; i++) {
            nextIndex = next[nextIndex];
            if (nextIndex == 3) {
                break;
            }
            cout << age[nextIndex] << endl;
        }
    }
}

void deleteLargest(int *next) {
    for (int i = 0; i < S; i++) {
        if (next[i] == 6) {
            if (i == 0) {
                cout << "Deleted All.";
                break;
            }
            next[i] = -2; // not used

            for (int j = 0; j < S; j++) {
                if (next[j] == i) {
                    next[j] = 6;
                }
            }
            break;
        }
    }
}

这些是我的数组的样子: [0] [1] [2] [3] [4] [5] [6] next(int) 3 6 4 5 -1 1 2 age(int) 9 12 7 15 8 11

根据rcgldr的推荐,我已经为这两个函数尝试了以下代码,但它似乎对我不起作用:(

    void deleteLargest(int *next) {
        for (int i = 0; i < S; i++) {
            if (next[i] == -1) {
                if (i == 0) {
                    cout << "Deleted all except age 7.";
                    break;
                }

                for (int j = 0; j < S; j++) {
                    if (next[j] == i) {
                        next[j] = -1;
                    }
                }
                break;
            }
        }
    }

0 个答案:

没有答案