注册 登录
编程论坛 C++教室

求解冒泡排序中遇到的问题

编程2011 发布于 2011-05-17 23:26, 428 次点击
程序代码:
#include<iostream>
#include<iomanip>
using namespace std;
void B(int  r[],int );
#include<ctime>
#include<cstdlib>
int main()
{
       const int M=100000;
    int size;
    int A[M];
     srand(time(0));
    for(int y=1;y<M;y++)
    {  
       A[y]=1+rand()%100000;
    }
    cout<<"请输入要排序的范围数:";
    cin>>size;
    cout<<endl;
     time_t first,end;
     first=clock();
    B(A,size);
    end=clock();
    cout<<"所需的时间为: "<<double(end-first);

 return 0;
}
void B(int r[], int n)
{
    int temp;
    int exchange;
    int bound;
    exchange=n-1;                       //第一趟起泡排序的范围是r[0]到r[n-1]   
    while (exchange)                    //仅当上一趟排序有记录交换才进行本趟排序
    {
        bound=exchange;
        exchange=0;
        for (int j=0; j<bound; j++)     //一趟起泡排序
        if (r[j]>r[j+1])
        {
          temp=r[j];
          r[j]=r[j+1];
          r[j+1]=temp;
          exchange=j;                   //记录每一次发生记录交换的位置
       }
    }
    for(int i=0;i<n;i++)
       cout<<r[i]<<setw(6);

}
假如你对随机产生的随机数进行排序,第一个数都是-858993460 其余的排序没错。为什么出现这种情况,请大家帮忙看看代码解释一下,谢谢了
5 回复
#2
寒风中的细雨2011-05-17 23:56
  for(int y=1;y<M;y++)
#3
编程20112011-05-18 00:07
回复 2楼 寒风中的细雨
这程序有问题?
#4
寒风中的细雨2011-05-18 00:11
下标值》》》》 零
#5
编程20112011-05-18 00:15
回复 4楼 寒风中的细雨
非常感谢。对了
#6
幸福的起点2011-05-18 09:40
回复 楼主 编程2011
我昨天也遇到这个问,这个是数组越界,也就是说你的下标达不到。给你一段参考代码
// bubble_sort.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
void bubble_sort(int a[],int n)
{
    int j,temp=0,m;
    while(temp<n)
        {
            for(j=0;j<n-temp-1;j++)
            {
                if(a[j]>a[j+1])
                {
                    m=a[j];
                    a[j]=a[j+1];
                    a[j+1]=m;
                }
            }
            temp++;
        }
    cout<<"sorted is:";
    for(int j=0;j<n;j++)
        cout<<a[j]<<"  ";
}
void main()
{
    int b[100],n;
    cout<<"please input the number of item:";
    cin>>n;
    for(int i=0;i<n;i++)
        {
            cout<<"please input  the"<<"  "<<i+1<<"  "<<"number:";
            cin>>b[i];
        }
    bubble_sort(b,n);
}

1