Number of swaps in Bubble Sort

QUESTION

You have been given an array A of size N you need to sort this array non-decreasing order using bubble sort. However, you do not need to print the sorted array . You just need to print the number of swaps required to sort this array using bubble sort\n\nInput Format\n\nThe first line consists of a single integer N\nN denoting size of the array. The next line contains N space separated integers denoting the elements of the array.\n\nOutput Format Print the required answer in a single line\n\nConstraints \n1<=N<=100\n1<=a[i]<=100.

“TESTCASE_1”: “5\n1 2 3 4 5\n###—###SEPERATOR—###—\n0”, “TESTCASE_2”: “100\n27 81 85 85 71 76 69 87 42 39 100 95 65 25 88 62 6 15 44 40 72 7 59 79 29 40 29 33 86 49 30 60 85 31 40 74 19 10 94 54 40 55 12 7 80 6 74 48 85 25 72 77 100 10 67 65 34 79 51 88 71 60 22 96 24 65 6 14 18 92 7 91 12 71 45 2 13 75 23 21 15 52 95 47 43 17 51 84 65 2 6 36 15 67 55 97 26 76 17 10\n###—###SEPERATOR—###—\n2788”, “TESTCASE_3”: “100\n91 76 23 7 61 68 20 21 72 87 18 52 13 89 48 93 97 50 71 3 32 73 70 24 27 11 96 85 33 20 83 29 29 64 57 90 43 90 8 92 86 61 55 73 16 87 30 7 94 19 18 68 80 98 95 6 64 81 81 98 91 79 2 94 25 82 88 71 95 75 17 20 64 34 94 49 22 44 18 97 84 54 31 72 61 83 63 39 70 7 71 27 71 77 17 77 8 79 30 11\n###—###SEPERATOR—###—\n2455”, “TESTCASE_4”: “0\n###—###SEPERATOR—###—\n0”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

#include <iostream>
using namespace std;
int main()
{int n,arr[100],count=0;
 cin>>n;
 for(int i=0;i<n;i++)
   cin>>arr[i];
 for(int i=0;i<n-1;i++)
 {for(int j=0;j<n-i-1;j++)
  {if(arr[j]>arr[j+1])
   {int temp=arr[j];
    arr[j]=arr[j+1];
    arr[j+1]=temp;
    count++;
   }
  }
 }
cout<<count;
 
 

	return 0;
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock