歸併排序以及逆序數計算

hi,主要注意兩點:

1、如果只用一份傳入的臨時數組,在merge的最後,要把所有元素,copy回原數組;

2、逆序數計算的時候 low2-i,而不是 low2-low1


其實還可以做一點優化,就是在merge函數裏,後半段如果沒結束,可以不用copy到臨時數組,

然後從臨時數組,copy回原數組的時候,可以少copy一段。


#include <iostream>
using namespace std;

int reverse_num = 0;

template<class T>
void print(T a[], int n) {
	for (int i=0; i<n; i++) {
	    cout << a[i] << " "; 
	}
	cout << endl;
}

void merge (int a[], int start, int mid, int end, int c[]) {
	int low1 = start;
	int low2 = mid+1;
	int i = start;
	while (low1 <= mid && low2 <= end) {
	    if (a[low1] > a[low2]) {
			c[i] = a[low2];

			reverse_num += (low2-i);
			low2++;
		} else {
		    c[i] = a[low1];
			low1++;
		}
		i++;
	}

	for (;low1 <= mid; low1++) {
	    c[i] = a[low1];
		i++;
	}
	for (;low2 <= end; low2++) {
	    c[i] = a[low2];
		i++;
	}

	for (int i=start; i<=end; i++) {
	    a[i] = c[i];
	}
}

void merge_sort (int a[], int start, int end, int c[]) {
    if (start >= end) {
		return;
	}

	int mid = (start + end)/2;

	merge_sort(a, start, mid, c);
	merge_sort(a, mid+1, end, c);
	merge(a, start, mid, end, c);
}

int main () {
    int a[] = {3,4,1,20,18,31,6,13};
	int size = sizeof(a)/sizeof(int);
	cout << size << endl;
	int c[size];

	print(a, size);
	merge_sort(a, 0, size-1, c);
	print(a, size);

	cout << "reverse_num:" << reverse_num << endl;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章