Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save arunavkonwar/c46e7a8f148cad4048695d455460b6df to your computer and use it in GitHub Desktop.

Select an option

Save arunavkonwar/c46e7a8f148cad4048695d455460b6df to your computer and use it in GitHub Desktop.
Bubble sort and finding the number of swaps done. https://www.hackerrank.com/challenges/ctci-bubble-sort
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
using namespace std;
int main(){
int n;
cin >> n;
vector<int> a(n);
for(int i = 0;i < n;i++){
cin >> a[i];
}
int numberOfSwapsMain=0;
for (int i = 0; i < n; i++) {
// Track number of elements swapped during a single array traversal
int numberOfSwaps = 0;
for (int j = 0; j < n - 1; j++) {
// Swap adjacent elements if they are in decreasing order
if (a[j] > a[j + 1]) {
swap(a[j], a[j + 1]);
numberOfSwaps++;
numberOfSwapsMain++;
}
}
// If no elements were swapped during a traversal, array is sorted
if (numberOfSwaps == 0) {
break;
}
}
cout<<"Array is sorted in "<<numberOfSwapsMain<<" swaps.";
cout<<"\nFirst Element: "<<a[0];
cout<<"\nLast Element: "<<a[n-1];
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment