![](/img/trans.png)
[英]How to calculate time in milliseconds of functions of bubble sort, insertion sort and selection sort in c++
[英]Bubble and Selection sort c++
我幾乎讓這段代碼起作用的唯一問題是我的選擇,氣泡排序正在刪除數組中的最后一個整數,並用零替換它,或者將其打印為零,而看不到數組中的最后一位數字。 無論如何都無法弄清楚如何解決該問題。 這是我的程序需要做的
通過創建一個1到49之間的6個值的隨機數組來開始程序。請確保您使用time()函數並使用srand作為rand()函數的種子。 使用將數組(及其大小)傳遞到的displaydata函數顯示結果數據。
讓用戶確定是否要使用冒泡排序對數組進行排序或選擇排序。 一旦用戶做出決定,程序就可以調用Bubblesort或selectionsort函數(以隨機數組及其大小作為參數),該函數對數組進行排序並調用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;
}
這個循環
for ( int i = 1; i < 7; i++ )
之所以被稱為Invald,是因為您嘗試訪問不屬於該數組的元素array [6]。 數組索引的有效范圍是[0,SIZE -1],即[0,5]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.