バブルソートではswapが使えるのに選択ソートでは使えないのでしょうか?
<バブルソート>
c++
1#include<iostream> 2using namespace std; 3 4int sort(int a[], int n) { 5 bool flag = true; 6 int sw = 0; 7 for (int i = 0;flag;i++) { 8 flag = false; 9 for (int j = n-1;j >=i+1;j--) { 10 if (a[j] < a[j - 1]) { 11 swap(a[j], a[j - 1]); 12 flag = true; 13 sw++; 14 } 15 } 16 } 17 return sw; 18} 19 20int main() { 21 int a[100], n, sw; 22 cin >> n; 23 for (int i = 0;i < n;i++) { 24 cin >> a[i]; 25 } 26 sw = sort(a, n); 27 for (int i = 0;i < n;i++) { 28 if (i) { 29 cout << " "; 30 } 31 cout << a[i]; 32 } 33 cout << endl << sw << endl; 34 35 return 0; 36}
<選択ソート>
c++
1#include<iostream> 2using namespace std; 3 4int sort(int a[], int n) { 5 int sw = 0; 6 for (int i = 0;i < n;i++){ 7 int minj = i; 8 for (int j = i;j < n;j++) { 9 if (j < i) { 10 swap(minj, i); 11 sw++; 12 } 13 } 14 } 15 return sw; 16} 17 18int main() { 19 int a[100], n,sw; 20 cin >> n; 21 for (int i = 0;i < n;i++) { 22 cin >> a[i]; 23 } 24 sw = sort(a, n); 25 for (int i = 0;i < n;i++) { 26 if (i > 0) { 27 cout << " "; 28 } 29 cout << a[i]; 30 } 31 cout << endl << sw << endl; 32 return 0; 33}
後者は入れ替えが行われません。どうしてですか?
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/04/15 06:04
2018/04/15 06:07