Advertisement
Guest User

Untitled

a guest
May 28th, 2017
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.62 KB | None | 0 0
  1. // Quicksort - see makefile for compiling options with G++.
  2. // Will not compile in VS2012 due to initialiser syntax in main() for std::vector
  3. #include <iostream>
  4. #include <vector>
  5. #include <algorithm> // Required
  6. #include <iterator> //Required
  7. #include <stdlib.h> // Required
  8. #include <time.h> // Required
  9.  
  10. // Function Prototypes
  11. int randomNumber(int start, int end); // Generate a number between start and end
  12.  
  13. // Perform QuickSort
  14. // Data provided will be modified
  15. template <typename Iterator> void quickSort(Iterator start, Iterator end){
  16. int size = (end - start);
  17. if ( size <= 0 )
  18. return; // Base case
  19.  
  20. // Partition - in place partitioning that involves only swapping
  21. // https://class.coursera.org/algo/lecture/preview/22 - O(n) time with no extra memory++
  22. /*
  23. Assume pivot is first element of array
  24. Otherwise swap pivot with first element
  25.  
  26. Idea: Array A is in this form
  27. pivot | < p | > p | unpartitioned/unseen
  28.  
  29. Let i = index of the first item > p
  30. Let j = index of the first item unpartitioned
  31.  
  32. Let i = 1
  33. Let j = 1
  34. Let p = pivot value
  35.  
  36. for j < size
  37. if A[i] < p
  38. swap A[j] with A[i]
  39. i++
  40. swap A[0] with A[i-1]
  41. */
  42. // Get pivot element
  43. int pivotIndex = randomNumber(0, size);
  44. typename std::iterator_traits<Iterator>::value_type pivot = *(start + pivotIndex);
  45.  
  46. if (pivotIndex != 0)
  47. std::swap(*(start + pivotIndex), *start);
  48.  
  49. int i = 1;
  50. for (int j = 1; j < size; j++){
  51. if ( *(start + j) < pivot ){
  52. std::swap( *(start+j), *(start+i));
  53. i++;
  54. }
  55. }
  56.  
  57. std::swap(*start, *(start + i - 1));
  58.  
  59. quickSort(start, start+i-1);
  60. quickSort(start+i, end);
  61. }
  62.  
  63. int main(){
  64. // This is C++11 syntax
  65. // Input must be unsigned
  66. std::vector<unsigned> input = {5,10,15,20,25,50,40,30,20,10,9524,878,17,1,99,18785,3649,164,94,
  67. 123,432,654,3123,654,2123,543,131,653,123,533,1141,532,213,2241,824,1124,42,134,411,
  68. 491,341,1234,527,388,245,1992,654,243,987};
  69.  
  70. quickSort(input.begin(), input.end());
  71.  
  72. // C++11 ranged based for loops
  73. // http://www.cprogramming.com/c++11/c++11-ranged-for-loop.html
  74. for (unsigned it : input){
  75. std::cout << it << std::endl;
  76. }
  77.  
  78. return 0;
  79. }
  80.  
  81. // Generate a number between start and end
  82. int randomNumber(int start, int end){
  83. // Seed the randomiser
  84. srand( time(NULL) );
  85.  
  86. return rand() % end + start;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement