Advertisement
skb50bd

Bubble Sort

Mar 29th, 2016
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.65 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main() {
  5.     int n;
  6.     cout << "Number of Elements: ";
  7.     cin >> n;
  8.  
  9.     int arr[n];
  10.  
  11.     cout << "Enter " << n << " Elements: ";
  12.     for(int i = 0; i < n; i++)
  13.         cin >> arr[i];
  14.  
  15.     bool swapped = true;
  16.     for(int j = 1; swapped; j++) {
  17.         swapped = false;
  18.         for (int i = 0; i < n - j; i++)
  19.                 if (arr[i] > arr[i + 1]) {
  20.                     swap(arr[i], arr[i + 1]);
  21.                     swapped = true;
  22.                 }
  23.     }
  24.  
  25.     cout << "Sorted Array: ";
  26.     for(int i = 0; i < n; i++)
  27.         cout << arr[i] << " ";
  28.     cout << endl;
  29.  
  30.     return 0;
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement