不动手敲一敲不知道会不会,把基础搞踏实了
一:归并排序,代码如下:
#include <iostream>
using namespace std;
#define ARR_SIZE 200
void m_merge(int* arr, int left, int middle, int right){
int tmp[ARR_SIZE];
int pos = left, p_begin = left;
int l_end = middle;
int r_begin = middle+1;
while(left <= l_end && r_begin <= right){
if(arr[left] <= arr[r_begin]){
tmp[pos++] = arr[left++];
}
else{
tmp[pos++] = arr[r_begin++];
}
}
while(left <= l_end){
tmp[pos++] = arr[left++];
}
while(r_begin <= right){
tmp[pos++] = arr[r_begin++];
}
for(int i = p_begin; i < pos; i++){
arr[i] = tmp[i];
}
}
void m_mergeSort(int* arr, int left, int right){
if(right > left){
int middle = (left + right)/2;
m_mergeSort(arr, left, middle);
m_mergeSort(arr, middle+1, right);
m_merge(arr, left, middle, right);
}
}
int main(int argc, char* argv[])
{
int testArr[] = {56, 3, 12, 98, 3, 6, 74, 0, 5, 88, 3};
int len = sizeof(testArr)/sizeof(int);
m_mergeSort(testArr, 0, len-1);
for(int i = 0; i < len; i++){
cout << testArr[i] << " ";
}
cout << endl;
return 0;
}
对于一些算法需要把握它的宏观思想,比如递归调用一直跟进它的细节就会看不见灿烂的天空了