Bubble Sort (Problem 27)

Back to General discussions forum

terryericland     2020-11-11 18:31:32

include <iostream>

using namespace std; int main() { int swap=0, pass=0, n; cin >> n; int a[n]; for(int i = 0; i < n; i++) cin >> a[i]; for(int i = 0; i < n; i++) { for(int k = i+1; k < n; k++) {
if(a[k] < a[i]) { int temp = a[i]; a[i] = a[k]; a[k] = temp; swap++; } } pass++; } cout << pass<< ' ' << swap; return 0; } The swap value is correct but I can't get the correct pass value, I don't know what to do. Any help?

Alexandr Milovantsev     2020-11-12 01:53:52

Because your code does not have condition to stop doing passes when array is already sorted.

Please login and solve 5 problems to be able to post at forum