ランダムに割り出した60個の数字が入ったアレーA[]をBubble sortで並べ換えるプログラムを書いています。
<期待する結果>
・ランダムな数字が入ったアレーを作る
・並べ換える前に1度プリントする(1行6個ずつ)
・アレーをBubble Sortで並べ換える
・それをプリントする
・アレーをBubble Sortで並べる(再帰を使って)
・それをプリントする
<実際の結果>
こちらのスクリーンショットは実際に自分が書いたプログラムをRunした時にプリントされた結果です。
ご覧の通り、1度目にBubble Sortした時に全ての数字が32767となっています。
また、再帰でBubble Sortをした時もまたアレー内の数字が変わっているようです。
<知りたいこと>
・どうしてこのように最初に割り出した数字と違う数字が1度目と2度目のBubble Sortで使われているのでしょうか?
・最初に割り出したランダムなアレーをBubble Sortで並べ換えるにはどうすれば良いですか?
C++初心者です。よろしければアドバイスよろしくお願いします。
c++
1#include <iostream> 2#include <ctime> 3using namespace std; 4void printUnsortedArray(int A[], int n); 5void bubbbleSort(int A[], int n); 6void bubbbleSort(int A[], int n); 7void swap(int A[], int i, int j); 8void printSortedArray(int A[], int n); 9 10void printUnsortedArray(int A[], int n){ 11 //define count for printing 6 per line 12 int count=0; 13 cout << "The array before sorting" <<endl; 14 for(int i=0; i<n; i++){ 15 //print num in array & space between each num 16 cout << A[i] <<" "; 17 count++; 18 //print new line after printing 6 nums 19 if(count==6){ 20 count=0; 21 cout << endl; 22 } 23 } 24 cout << "\n"; 25} 26 27void bubbbleSort(int A[], int n){ 28 int i,j; 29 for(i=0; i<n-1; i++){ 30 for(j=0; j<n-1; j++){ 31 if(A[j]>A[j+1]) 32 swap(A,i,i+1); 33 } 34 } 35} 36 37void bubbleSortRec(int A[], int n){ 38 int i; 39 for(i=0; i<n-1; i++){ 40 if(A[i]>A[i+1]) 41 swap(A,i,i+1); 42 } 43 if(n-1>1) 44 bubbleSortRec(A,n-1); 45} 46 47void swap(int A[], int i, int j){ 48 int tmp; 49 A[i]=A[j]; 50 A[j]=tmp; 51} 52 53void printSortedArray(int A[], int n){ 54 //define count for printing 6 per line 55 int count=0; 56 cout << "The array after sorting" <<endl; 57 for(int i=0; i<n; i++){ 58 //print num in array & space between each num 59 cout << A[i] <<" "; 60 count++; 61 //print new line after printing 6 nums 62 if(count==6){ 63 count=0; 64 cout << endl; 65 } 66 } 67 cout << "\n"; 68} 69 70int main(){ 71 //create array 72 int A[60]; 73 srand(time(NULL)); 74 75 for(int i=0; i<sizeof(A); i++) 76 A[i]=rand()%100; 77 78 int n=sizeof(A)/sizeof(A[0]); 79 80 //call functions 81 printUnsortedArray(A,n); 82 bubbbleSort(A,n); 83 printSortedArray(A,n); 84 bubbleSortRec(A,n); 85 printSortedArray(A,n); 86 87 return 0; 88 89} 90
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/02/10 04:23
2018/02/10 05:34 編集