Advertisement
RnD

C++ Bubble Sort algorithm

RnD
Jun 13th, 2012
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.77 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. int main(){
  4.  
  5.     int n, temp, j=0; //additional vars
  6.     bool swapped = true;
  7.     std::cin >> n; //inputing the index of array
  8.  
  9.     int arr[n];
  10.     for(int i=0;i<n;i++){
  11.         std::cin >> arr[i];
  12.     }
  13.  
  14.     while(swapped){ //do this loop until everything is swapped in it's order
  15.         swapped = false;
  16.         j++;
  17.  
  18.         for(int i=0;i<n-j;i++){ //n-j is important if we don't want to loop the same number twice
  19.             if(arr[i]>arr[i+1]){
  20.                 temp = arr[i];
  21.                 arr[i] = arr[i+1];
  22.                 arr[i+1] = temp;
  23.                 swapped = true;
  24.             }
  25.         }
  26.     }
  27.  
  28.     for(int i=0;i<n;i++){ //let's check if everything's in order
  29.         std::cout<<arr[i]<<" ";
  30.     }
  31.  
  32.     return 0;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement