randomized_quicksort

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include "chapter-7/quicksort/quicksort.h"
namespace CLRS
{
  template <typename T, std::size_t n>
  std::size_t randomized_partition(T (&a)[n], long long p, long long r)
  {
    std::default_random_engine e(std::time(0));
    std::uniform_int_distribution<long long> u(p, r);
    long long i = u(e);
    T temp = a[r];
    a[r] = a[i];
    a[i] = temp;
    return CLRS::partition(a, p, r);
  }

  template <typename T, std::size_t n>
  void randomized_quicksort(T (&a)[n], long long p, long long r)
  {
    if(p < r)
      {
	std::size_t q = randomized_partition(a, p, r);
	randomized_quicksort(a, p, q - 1);
	randomized_quicksort(a, q + 1, r);
      }
  }
}

quicksort

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
namespace CLRS
{
  template <typename T, std::size_t n>
  std::size_t partition(T (&a)[n], long long p, long long r)
  {
    T x = a[r];
    std::size_t i = p;
    for(std::size_t j = p; j != r; ++j)
      {
	if(a[j] <= x)
	  {
	    T temp = a[i];
	    a[i] = a[j];
	    a[j] = temp;
	    ++i;
	  }
      }
    T temp = a[i];
    a[i] = a[r];
    a[r] = temp;
    return i;
  }

  template <typename T, std::size_t n>
  void quicksort(T (&a)[n], long long p, long long r)
  {
    if(p < r)
      {
	std::size_t q = partition(a, p, r);
	quicksort(a, p, q - 1);
	quicksort(a, q + 1, r);
      }
  }
}