Code Snippets

  

C++ Source Code


Welcome to Dream.In.Code
Become a C++ Expert!

Join 149,619 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,878 people online right now. Registration is fast and FREE... Join Now!





Bubble Sort

Implementation of bubble sorting algorithm.

Submitted By: k0b13r
Actions:
Rating:
Views: 6,994

Language: C++

Last Modified: April 12, 2007
Instructions: x > y - ascending sort
x < y - descending sort

Snippet


  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int compare(int, int);
  5. void sort(int[], const int);
  6. void swap(int *, int *);
  7.  
  8. int compare(int x, int y)
  9. {
  10.      return(x > y);
  11. }
  12.  
  13. void swap(int *x, int *y)
  14. {
  15.      int temp;
  16.      temp = *x;
  17.      *x = *y;
  18.      *y = temp;
  19. }
  20.  
  21. void sort(int table[], const int n)
  22. {
  23.      for(int i = 0; i < n; i++)
  24.      {
  25.           for(int j = 0; j < n-1; j++)
  26.           {
  27.                if(compare(table[j], table[j+1]))
  28.                     swap(&table[j], &table[j+1]);
  29.           }
  30.      }
  31. }
  32.  
  33. int quantity;
  34. int* tab;
  35.  
  36. int main()
  37. {
  38. cout << "Input quantity: ";
  39. cin >> quantity;
  40. tab = new int [quantity];
  41. cout << "Input numbers: \n\n";
  42. for (int i = 0; i < quantity; i++)
  43. {
  44.     int x = i;
  45.     cout << "#" << ++x << ": ";
  46.     cin >> tab[i];
  47. }
  48.  
  49. cout << "\nBefore sorting: ";
  50. for (int i = 0; i < quantity; i++)
  51. {
  52.      cout << tab[i] << " ";
  53. }
  54.  
  55. cout << "\nAfter sorting: ";
  56. sort(tab, quantity);
  57. for(int i = 0; i < quantity; i++)
  58. {
  59.      cout << tab[i] << " ";
  60. }
  61. return 0;
  62. }
  63.  

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.




Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month