当前位置: 代码迷 >> 综合 >> 输出数组的全排列,用c++实现。
  详细解决方案

输出数组的全排列,用c++实现。

热度:51   发布时间:2024-02-28 14:33:53.0

// DataStructure01.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//本次程序是20201014第一次数据结构课程实验,未来可期,加油努力

#include <iostream>
using namespace std;
int count1 = 0;

void Output(int* outOb, int size);//问题 用for循环代替while循环 在方法的参数列表中加入一个size使其避免超界
int Input(int* ob) {
    cout << "Input" << endl;
    for (int i = 0; i < 20; i++) {
        cin >> ob[i];
        if (ob[i] == 0) return i - 1;
    }
    return 19;
}; //注意size是下表而非大小
void Output(int* outOb,int size) {
    for (int i = 0; i < size; i++) 
    {
        cout << outOb[i]<<",";
        }
    cout << outOb[size];
}
void SwapElement(int& one, int& theOther)
{
    int temp1;
    temp1 = one;
    one = theOther;
    theOther = temp1;
}
void End0();
void Permution(int* ob, int m1, int n1,int size) {
    if (m1 == n1 )
    {
        count1++;
        Output(ob, size);//要用到的都需要通过函数列表传过来
        cout << endl;
    }
    for (int i = m1; i <=n1; i++) {
        if (i == m1)//i==m1时无需交换数组的两个元素
            Permution(ob, m1 + 1, n1, size);
        else {
            SwapElement(ob[i], ob[m1]);
            Permution(ob, m1 + 1, n1,size);
            SwapElement(ob[i], ob[m1]);

        }
    }
}

int main()
{
    int Object[20];
    int size = 0;
    size=Input(Object);
   
    cout << "Output" << endl;
    Permution(Object, 0, size, size);
    cout << "end";
    return 0;
}

 

  相关解决方案