merge_sort

 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
namespace CLRS
{
  template <typename T>
  void merge(T *array, std::size_t p, std::size_t q, std::size_t r)
  {
    std::size_t n1 = q - p + 1;
    std::size_t n2 = r - q;
    T larray[n1], rarray[n2];
    for(std::size_t i = 0; i < n1; ++i)
      larray[i] = array[p + i];
    for(std::size_t j = 0; j < n2; ++j)
      rarray[j] = array[q + j + 1];

    std::size_t i = 0, j = 0, k = p;
    while(k <= r)
      {
	if(i < n1 && j == n2)
	  {
	    array[k] = larray[i];
	    ++i;
	  }
	else if(i == n1 && j < n2)
	  {
	    array[k] = rarray[j];
	    ++j;
	  }
	else if(larray[i] <= rarray[j])
	  {
	    array[k] = larray[i];
	    ++i;
	  }
	else
	  {
	    array[k] = rarray[j];
	    ++j;
	  }
	++k;
      }
  }

  template <typename T>
  void merge_sort(T *array, std::size_t p, std::size_t r)
  {
    if(p < r)
      {
	std::size_t q = (p + r) / 2;
	merge_sort(array, p, q);
	merge_sort(array, q + 1, r);
	merge(array, p, q, r);
      }
  }
}

insertion_sort

 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
namespace CLRS
{
  template <typename T, std::size_t n> void insertion_sort(T (&array)[n])
  {
    /*
     * for std::size_t is a alias of unsigned long,
     * and the index in while loop must not be an unsigned,
     * then index should be long long which could
     * accommodate the maximum unsigned long integer
     * to avoid bug.
     */
    if(n <= 1)
      // in this case there is no need to sort.
      return;
    for(long long j = 1; j != n; ++j)
      {
	T temp = array[j];
	long long i = j - 1;
	while(i >=0 && array[i] > temp)
	  {
	    array[i + 1] = array[i];
	    --i;
	  }
	array[i + 1] = temp;
      }
  }
}