快速排序和归并排序

quick_sort() 快速排序
merge_sort() 归并排序

#include
#include
using namespace std;
const int N = 100010;
/*快速排序算法*/
void quick_sort(int arr[], int l, int r) {
	if (l >= r) {
		return ;

	}
	int left = l - 1;
	int right = r + 1;
	int mid = (l + r) / 2;
	while (left < right) {
	
		do {
			left++;
			//TODO
		} while (arr[left] < arr[mid]);
		do {
			right--;
			//TODO
		} while (arr[right] > arr[mid]);
		if (left < right) {
			swap(arr[left], arr[right]);
		}
	}
	quick_sort(arr, l, right);
	quick_sort(arr, right + 1, r);

}



/*main函数*/
int main() {
	int n = 0;
	scanf("%d", &n);
	int arr[N];
	for (int i = 0; i < n; i++) {
		scanf("%d", &arr[i]);  //
	}

	quick_sort(arr, 0, n - 1);

	for (int i = 0; i < n; i++) {
		printf("%d ", arr[i]);
	}
	return 0;
}

#include
#include
using namespace std;
const int N = 100010;

int arr[N];
int tmp[N];
/*merge 归并排序*/
void merge_sort(int arr[], int l, int r) {
	if (l >= r) {
		return ;
	}
	int mid = (l + r) >> 1;
	merge_sort(arr, l, mid); // 先划分
	merge_sort(arr, mid + 1, r);

	int k = 0;
	int i = l, j = mid + 1;
	while (i <= mid && j <= r) { //排序合并
		if (arr[i] <= arr[j]) {
			tmp[k++] = arr[i++];
		} else {
			tmp[k++] = arr[j++];
		}
		//TODO
	}
	// 扫尾
	while (i <= mid) {
		tmp[k++] = arr[i++];
	}
	while (j <= r) {
		tmp[k++] = arr[j++];
	}
	// 赋值给原数组
	for (int i = l, x = 0; i <= r; i++) {
		arr[i] = tmp[x++];
	}
}




/*main函数*/
int main() {
	int n = 0;
	scanf("%d", &n);

	for (int i = 0; i < n; i++) {
		scanf("%d", &arr[i]);  //
	}

	merge_sort(arr, 0, n - 1);

	for (int i = 0; i < n; i++) {
		printf("%d ", arr[i]);
	}
	return 0;
}

你可能感兴趣的:(排序算法,算法,数据结构)