算法 -- 归并排序
归并算法(排序)
缺点:特消耗空间
代码
#pragma once #include <stdlib.h> #include <stdio.h> class MergerSort { public: MergerSort(void); ~MergerSort(void); public: void breakOut(int *arr, const int first, const int mid, const int last); void mergeSort(int *array, const int first, const int last); void print(const int first, const int len, const int *arr); }; MergerSort::MergerSort(void) { } MergerSort::~MergerSort(void) { } void MergerSort::breakOut(int *arr, const int first, const int mid, const int last) { int* tmp; tmp = (int*)malloc((last-first+1)*sizeof(int)); if(tmp == NULL) return; int fir1 = first; int last1 = mid; int fir2 = mid+1; int last2 = last; int index = 0; while( (fir1<=last1) && (fir2<=last2)) { if(arr[fir1] < arr[fir2]) { tmp[index++] = arr[fir1++]; } else { tmp[index++] = arr[fir2++]; } } while( fir1 <= last1) tmp[index++] = arr[fir1++]; while( fir2 <= last2) tmp[index++] = arr[fir2++]; for(int i=0; i<(last-first+1); i++) { arr[first+i] = tmp[i]; } free(tmp); } void MergerSort::mergeSort(int *array, const int first, const int last) { int mid=0; if(first < last) { mid=(first+last)/2; mergeSort(array,first,mid); mergeSort(array,mid+1,last); breakOut(array,first,mid,last); print(first, last-first+1, array+first); } } void MergerSort::print(const int first, const int len, const int *arr) { static int count = 0; printf("(%2d)", count++); for(int i=0; i<first; i++) { printf(" "); } for(int i=0; i<len; i++) { printf("%3d ", arr[i]); } printf("\n"); }
浙公网安备 33010602011771号