Sort(Ⅱ)

Now let’s see 2 NIUBI algorithms.

  1. mergeSort:
    thinking:
    (1) a simple way is merging 2 different arrays into the third array
    however, there is a lot of waste of memory-- so we divide the array into 2 subarrays and merge them finally
 template
 void merge(T a[], int lo, int mid, int hi){
  int i=lo, j=mid+1;   //merge a[lo..mid] and a[mid+1..hi]
  T tmp[hi-lo+1];
  for (int k=lo;k<=hi;k++) tmp[k] = a[k];
  for (int k=lo;k<=hi;k++)
     if      (i > mid)           a[k] = tmp[j++];  // the left side has nothing left 
     else if (j > hi)            a[k] = tmp[i++];  // the right side has nothing left
     else if (tmp[j] < tmp[i]) a[k] = tmp[j++];    // compare the current elements of each subarray          
     else                      a[k] = tmp[i++];
    
}

(2) we need a method to merge, and the we use recursion to sort the array.
(3) In fact, their are 2 ways to finish the issue.
a. from the top to the bottom:

template
void mergeSort(T a[], int lo, int hi){
  if (hi<=lo) return;
  int mid = lo + (hi-lo)/2;
  mergeSort(a, lo ,mid);      // sort the left
  mergeSort(a, mid+1, hi);    // sort the right
  merge(a, lo, mid, hi);      // merge them together
 }

b. from the bottom to the top:

template
void mergeSort(T a[], int n){
  for (int sz=1; sz

evaluate:
(1) nlogn
(2) there must be a waste of memory for merge method, however, it is very fast.

  1. quickSort:
    thinking:
    (1) Divide the array into 2 subarrays, the partition method is crucial.
    (2) When the 2 subarrays are done for sorting, the whole array is done too.
    (3) we use recursion to accomplish this.
template
int partition(T a[], int lo, int hi) {
	int i = lo, j = hi + 1;
	T v = a[lo];
	while (1) {
		while (a[++i] < v)
			if (i == hi)
				break;
		while (v < a[--j])
			if (j == lo)
				break;
		if (i >= j)
			break;
		swap(a[i], a[j]);
	}
	swap(a[lo], a[j]);
	return j;
}

then we come for the quickSort:

template
void quickSort(T a[], int lo, int hi) {
	if (hi <= lo)
		return;
	int j = partition(a, lo, hi);
	quickSort(a, lo, j - 1);
	quickSort(a, j + 1, hi);
}

evaluate:
(1) it can be deemed as the best algorithm of sorting.
(2) we choose a fixed value to compare with, and the times for comparations are very few.

你可能感兴趣的:(总结笔记)