C++ Bubble Sort Algorithm Using Tempaltes


/ Published in: C++
Save to your folder(s)

Here I present a modern template based approach to a bubble sorting algorithm. The complexity of this algorithm runs in O(n^2) order of complexity.


Copy this code and paste it in your HTML
  1. #include "stdafx.h"
  2.  
  3. /** Core bubble sort algorithm. */
  4. template<class T>
  5. void BubbleSort(T* pElements, size_t uNumElements, int (*pComparison)(T const* pA, T const* pB))
  6. {
  7. for(int i = 0; i < uNumElements; i++)
  8. {
  9. for(int j = i+1; j < uNumElements; j++)
  10. {
  11. int iCompare = pComparison(&pElements[i], &pElements[j]);
  12. if(iCompare > 0)
  13. {
  14. T tSwapElement = pElements[i];
  15. pElements[i] = pElements[j];
  16. pElements[j] = tSwapElement;
  17. }
  18. }
  19. }
  20. }
  21.  
  22. /** Comparison function passed to bubble sort. */
  23. int IntCompare(int const* pA, int const* pB)
  24. {
  25. return *pA - *pB;
  26. }

URL: http://snippetking.com/View/35/a-modern-approach-to-a-bubble-sort-algorithm-implementation

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.