当前位置:编程学习 > C/C++ >>

C++怎样实现数组随机排序输出

恩希望把方法说一下,不要代码
追问:来自手机问问你这不是抄的那个洗牌程序嘛,
答案://在MIX();实现的时候已经说明

//随机查找数组的脚标限制为数组最大脚标以内,和默认的第temp进行交换

//name:mix.h
//author:_a_qian
//update:2010/6/2
//edition:1.0.0.1
//
//
#ifndef MIX_H_
#define MIX_H_

class mix
{
public:
 mix(int = 54,bool=true);//参数一:多少个;参数二:是否写入*默认值*
 ~mix();
 void initialize_zero();//清理所有值
 bool exchange(int,int);//交换数;参数一:前一个数的位置,从0起;参数二:后一个数的位置,从0起
 void compositor();//排序
 void MIX();//打乱
 void showcard();//显示所有有效数
 void writecard();//写默认值
private:
 int *cards;
 const int Max;
};
/*
*默认值*:分配所有数初始化为最大数值
*/
#endif

//————————————————————分页行————————————

//————————————————————分页行————————————

//name:mix_class.cpp
//author:_a_qian
//update:2010/6/2
//edition:1.0.0.1
//
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
#include"mix.h"
mix::mix(int many, bool overwrite):Max(many)
{
 cards=new int[Max];
 initialize_zero();
 if(overwrite)
 {
  writecard();
  MIX();
 }
}
mix::~mix()
{
 delete cards;
 cards=NULL;
}
void mix::initialize_zero()
{
 for(int temp=0;temp<this->Max;temp++)
 {
  *(cards+temp)=0;
 }
}
void mix::MIX()//打乱函数
{
 srand((unsigned)time(NULL));
 for(int temp=0;temp<Max;temp++)
 {
  exchange(temp,rand()%Max);//随机查找数组的脚标限制为数组最大脚标以内,和默认的第temp进行交换
 }

}

bool mix::exchange(int one, int two)
{
 if(one<0 || one>=Max||two<0 || two>=Max){return false;}//超出寻址范围
 swap(*(cards+one),*(cards+two));
 return true;
}
void mix::writecard()
{
 for(int temp=0;temp<Max;temp++)
 {
  *(cards+temp)=temp+1;
 }
}
void mix::compositor()
{
 int Maxx=0;
 for(int temp=0;temp<Max;temp++)
 {
  Maxx=temp;
  for(int Ma=temp+1;Ma<Max;Ma++)
  {
   if(*(cards+Maxx)>*(cards+Ma))
   {
    Maxx=Ma;
   }
  }
  exchange(temp,Maxx);
 }
}
void mix::showcard(){
 for(int a=0;a<Max;a++){
  cout<<"   "<<*(cards+a)<<"   ";
 }

}

//————————————————————分页行————————————

//————————————————————分页行————————————

//name:text_main.cpp
//author:_a_qian
//update:2010/6/2
//edition:1.0.0.1
//
//
#include<iostream>
#include"mix.h"
void main(){
mix a;//已经打乱
a.showcard();
std::cout<<std::endl<<std::endl<<std::endl;

a.MIX();//再次打乱
a.showcard();
std::cout<<std::endl<<std::endl<<std::endl;

a.compositor();//排序
a.showcard();
std::cout<<std::endl<<std::endl<<std::endl;

a.MIX();//再次打乱
a.showcard();
std::cout<<std::endl<<std::endl<<std::endl;
}

//————————————————————分页行————————————

上一个:谁能解释下这个C++什么意思
下一个:C语言跟C++有什么不同?

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,