使用随机函数初始化一个数组,并对数组进行排序(冒泡排序法和选择排序法)

来源:互联网 发布:licecap for windows 编辑:程序博客网 时间:2024/05/12 09:01
使用C++随机函数Rand()生成n个数,采用冒泡排序法.选择排序法这两种方法对n个数进行排序,要求用函数来实现。
[ 标签:c++,随机函数,rand ] 绿蓑衣(Lian 回答:1 人气:1 解决时间:2010-12-23 09:24
满意答案好评率:100% #include <iostream>
#include <string>
#include <ctime>
using namespace std;

void Maopao_sort(int array[] ,int n)
{//冒泡排序
 int tmp;
 for(int i = 0; i < n-1; i++)
 {
  for(int j = 0; j < n - i-1; j++)
  {
   if(array[j] < array[j+1])
   {
    tmp = array[j+1];
    array[j+1] =array[j];
    array[j] = tmp;
   }
  }
 }
}

void Select_sort(int array[],int n)
{//选择排序
 int small;//临时变量寄存器
 for(int i=0;i<n-1;i++)
 {
    small = i;
    for(int j=i+1;j<n;j++)
    {
   if(array[small] > array[j])
   {
    small = j;
   }
    }
   if(small!=i)
      {
   int t = array[small];
   array[small]=array[i];
   array[i]=t;
   }
   }
}

void main()
{
 int num_ary[10];
 cout << "原数组顺序:" << endl;
 srand((unsigned int) time(0));
 for(int i = 0 ; i < sizeof(num_ary)/4 ;i++)
 {

  num_ary[i] = rand()%50;//随机50之间的数字来 初始化数组num_ary
  cout << num_ary[i] << endl;
 }
 Select_sort(num_ary ,sizeof(num_ary)/4);//选择排序从小到大

 cout << "选择排序从小到大:" << endl;
 for(int i = 0 ; i < sizeof(num_ary)/4 ;i++)
 {
  cout << num_ary[i] << " ,";
 }

 cout << endl;

 Maopao_sort(num_ary ,sizeof(num_ary)/4);//冒泡排序从大到小
 cout << "冒泡排序从大到小:" << endl;
 for(int i = 0 ; i < sizeof(num_ary)/4 ;i++)
 {
  cout << num_ary[i] << " ,";
 }
}