【发布时间】:2013-12-01 18:42:16
【问题描述】:
我几乎让这段代码正常工作,唯一的问题是我的选择和冒泡排序正在删除我数组中的最后一个整数并用零替换它,或者它打印一个零并且看不到数组中的最后一个数字。无论如何无法弄清楚如何解决这个问题。这是我的程序需要做的事情
通过创建一个包含 1 到 49 之间的 6 个值的随机数组来开始程序。确保使用 time() 函数和 srand 为 rand() 函数提供种子。使用您将数组(及其大小)传递到其中的 displaydata 函数显示结果数据。
让用户确定他们是希望使用冒泡排序还是选择排序来对数组进行排序。一旦用户做出决定,让程序调用冒泡排序或选择排序函数(以随机数组及其大小作为参数)对数组进行排序并调用 displaydata 函数(以排序后的数组作为参数)。
[代码]
#include <iostream>
#include<time.h>
using namespace std;
const int SIZE = 6;
void displaydata ( int[], int );
void bubblesort ( int[], int );
void selectionsort ( int[], int );
int main()
{
char choice;
int array [ SIZE ] = {0,0,0,0,0,0};
srand ( ( int ) time ( 0 ) );
for ( int i = 0; i < SIZE; i++ )
{
array [ i ] = 1 + ( rand() % 49 );
}
cout << "Do you wish to use Bubble Sort (Enter 'B') or Selection Sort (Enter 'S'): ";
cin >> choice;
cout << endl;
displaydata ( array, SIZE );
if ( choice == 'b' || choice == 'B' )
{
bubblesort ( array, SIZE );
}
else if ( choice == 's' || choice == 'S' )
{
selectionsort ( array, SIZE );
}
else
{
cout << " Invalid Entry ";
}
return 0;
}
void displaydata ( int array[], int size )
{
cout<<"----------------\n";
cout<<" Original Array \n";
cout<<"----------------\n\n";
/* loop 5 times */
for (int size = 1; size < 7; size++ )
{
cout << array [ size ] << endl;
}
}
void bubblesort ( int array[], int b )
{
for( int i=1; i<b ;i++ )
{
for( int a=0; a<b-1; a++)
{
if(array[a] > array[a+1])
{
int temp;
temp = array[a];
array[a] = array[a+1];
array[a+1] = temp;
}
}
}
cout<<endl;
cout<<"-------------------\n";
cout<<" Bubble Sort Array \n";
cout<<"-------------------\n\n";
for( int a=0; a<b; a++)
cout<<array[a]<<endl;
}
void selectionsort ( int array[], int s )
{
int pos_min,temp;
for (int i=0; i < s-1; i++)
{
pos_min = i;
for (int j=i+1; j < s; j++)
{
if (array[j] < array[pos_min])
pos_min=j;
}
if (pos_min != i)
{
temp = array[i];
array[i] = array[pos_min];
array[pos_min] = temp;
}
}
cout<<endl;
cout<<"----------------------\n";
cout<<" Selection Sort Array \n";
cout<<"----------------------\n\n";
for( int a=0; a<s; a++)
cout<<array[a]<<endl;
}
【问题讨论】: