注册 登录
编程论坛 数据结构与算法

您好,我想请问一下随机产生三个数,并从小到大输出的代码怎么写,求答

不玩虚的 发布于 2013-05-11 06:23, 1000 次点击
[i]#include <iostream>
using namespace std;
template<class Type>
void Swap(Type *array,Type a,Type b)
{    Type temp;
    temp=array[a];
    array[a]=array[b];
    array[b]=temp;
}
template<class Type>
void FastSort(Type *array,Type n)
{    for(int i=0;i<n;i++)
    {    for(int j=i;j>0;j--)
        {    if(array[j]<array[j-1])
            Swap(array,j,j-1);
        }
        //else break;
    }

}//上面只是一个排序算法,可以用别的替换
int main()
{        int *b;
    b=new int [3];
    for(int i=0;i<3;i++)//产生3个0-9随机数,注意是假随机数//放在一数组中
    {int a=rand()%10;
    b=a;
    }
    FastSort(b,3);
    for(int j=0;j<3;j++)
    {    cout<<b[j]<<" ";
    }
    cout<<endl;
    return 0;
}
4 回复
#2
笑傲2013-05-11 11:25
你的代码的思想没什么问题啊,只是有一个地方写错了,
b = a;应该是b[i] = a;
#3
不玩虚的2013-05-11 14:03
//我那个去了,这复制粘贴这么不好用啊,居然把那个[i]粘贴在头文件之前了,谢谢啦
#include <iostream>
 using namespace std;
 template<class Type>
 void Swap(Type *array,Type a,Type b)
 {    Type temp;
     temp=array[a];
     array[a]=array[b];
     array[b]=temp;
 }
 template<class Type>
 void FastSort(Type *array,Type n)
 {    for(int i=0;i<n;i++)
     {    for(int j=i;j>0;j--)
         {    if(array[j]<array[j-1])
             Swap(array,j,j-1);
         }
         //else break;
     }
 
}//上面只是一个排序算法,可以用别的替换
 int main()
 {        int *b;
     b=new int [3];
     for(int i=0;i<3;i++)//产生3个0-9随机数,注意是假随机数//放在一数组中
     {int a=rand()%10;
     b[i]=a;
     }
     FastSort(b,3);
     for(int j=0;j<3;j++)
     {    cout<<b[j]<<" ";
     }
     cout<<endl;
     return 0;
 }
#4
笑傲2013-05-11 17:39
其实我想说你不是已经写出来了嘛,
感觉你是在秀代码;
#5
不玩虚的2013-05-11 22:27
我是帮人弄的,不好意思啊,别介意啊
1