归并排序,大佬的代码,注释也写的很好
/* Merge sort in C++ */
#include <cstdio>
#include <iostream>
using namespace std;
// Function to Merge Arrays L and R into A.
// lefCount = number of elements in L
// rightCount = number of elements in R.
//归并
void Merge(int *A,int *L,int leftCount,int *R,int rightCount) {
int i,j,k;
// i - to mark the index of left aubarray (L)
// j - to mark the index of right sub-raay (R)
// k - to mark the index of merged subarray (A)
i = 0; j = 0; k =0;
while(i<leftCount && j< rightCount) {
if(L[i] < R[j]) A[k++] = L[i++]; //先放小的
else A[k++] = R[j++];
}
while(i < leftCount) A[k++] = L[i++]; //如果一个先放完了,剩下的直接添加到后面
while(j < rightCount) A[k++] = R[j++];
}
// Recursive function to sort an array of integers.
//递归,并排序
void MergeSort(int *A,int n) {
int mid,i, *L, *R; //n是数组元素个数
if(n < 2) return; // base condition. If the array has less than two element, do nothing.
mid = n/2; // find the mid index.
//会不会出现不能整除的现象,这种现象回有影响嘛?
// create left and right subarrays
// mid elements (from index 0 till mid-1) should be part of left sub-array
// and (n-mid) elements (from mid to n-1) will be part of right sub-array
//自己创建左右子数组
L = new int[mid]; //每递归一次都会new一个新的出来
R = new int [n - mid];
//给子数组赋值
for(i = 0;i<mid;i++) L[i] = A[i]; // creating left subarray
for(i = mid;i<n;i++) R[i-mid] = A[i]; // creating right subarray
MergeSort(L,mid); // sorting the left subarray
MergeSort(R,n-mid); // sorting the right subarray
Merge(A,L,mid,R,n-mid); // Merging L and R into A as sorted list.
// the delete operations is very important
delete [] R; //释放申请的内存
delete [] L;
}
int main() {
/* Code to test the MergeSort function. */
int A[] = {6,2,3,1,9,10,15,13,12,17}; // creating an array of integers.
int i,numberOfElements;
// finding number of elements in array as size of complete array in bytes divided by size of integer in bytes.
// This won't work if array is passed to the function because array
// is always passed by reference through a pointer. So sizeOf function will give size of pointer and not the array.
// Watch this video to understand this concept - http://www.youtube.com/watch?v=CpjVucvAc3g
numberOfElements = sizeof(A)/sizeof(A[0]);
// Calling merge sort to sort the array.
MergeSort(A,numberOfElements); //传入数组起始地址和元素个数
//printing all elements in the array once its sorted.
for(i = 0;i < numberOfElements;i++)
cout << " " << A[i];
return 0;
}