算法导论第4章 分治

分治法意在将大的问题分解成足够小的问题进行求解,并将得出的答案进行归并得到最终的答案
二分法排序属于一种分治。
先将一个数组进行分割,直至子数组中只剩下一个元素,再进行比较。流程如下图



代码:
#pragma once

#include "targetver.h"

#include <stdio.h>
#include <tchar.h>
#include <stdlib.h>
#include <time.h>
#include <Windows.h>
class stdFunc{
private:

public:
    static int I_start_time;
    static void setseed();
    static int random();
    static int random(int max);
    static int random(int min, int max);
    static void mergesort(int i_array[], int i_left, int i_right, int temp[]);
    static void msort(int i_array[], int i_len);
    static void recordtime();
    static int getruntime();
};

 

#include "stdafx.h"


int stdFunc::I_start_time = 0;
int stdFunc::random(){
    return rand();
}

int stdFunc::random(int max){
    return rand() % max;
}

int stdFunc::random(int min, int max){
    return min + (rand() % max);
}

void stdFunc::setseed(){
    srand((int)time(0));
}

void stdFunc::msort(int i_array[], int i_len){
    int *t = new int[i_len];
    mergesort(i_array, 0, i_len, t);
    //delete[] t;
}
 
void stdFunc::mergesort(int i_array[], int i_left, int i_right, int temp[]) {
    int mid = (i_right + i_left) / 2;
    //if subarray has more than two elements than sub it
    if (i_right>i_left){
        mergesort(i_array, i_left, mid,temp);
        mergesort(i_array, mid + 1, i_right,temp);
    }
    int i = i_left, j = mid+1,k = 0;
    //Compare two Arrays' Element and put the smaller(or bigger) one into temp[]
    while (i <= mid && j <=i_right){
        if (i_array[i] <= i_array[j]){
            temp[k++] = i_array[i];
            i++;
        }
        else{
            temp[k++] = i_array[j];
            j++;
        }
    }
    //Copy Element in sort into Array Temp[]
    while (i <= mid){
        temp[k++] = i_array[i++];
    }
    while (j <= i_right){
        temp[k++] = i_array[j++];
    }
    //Copy Elements in Temp[] into i_array
    for (int i = 0; i < k; i++){
        i_array[i_left + i] = temp[i];
    }
    
}

void stdFunc::recordtime(){
    //record start time
    I_start_time = GetTickCount();
}

int stdFunc::getruntime(){
    //calculate runtime
    return GetTickCount() - I_start_time;
}
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
    int *i_array;
    int i_numsize;
    stdFunc::setseed();
    printf("Please set number Size:\n");
    //get Array size
    scanf("%d", &i_numsize);
    //malloc memory by Arraysize
    i_array = new int[i_numsize];
    //Random number and save to i_array
    for (int index = 0; index < i_numsize; index++){
        i_array[index] = stdFunc::random(100);
    }
    stdFunc::recordtime();
    //call sort Function
    stdFunc::msort(i_array, i_numsize - 1);
    printf("Megre Finish in %d ms\n", stdFunc::getruntime());
    /*for (int index = 0; index < i_numsize; index++){
        printf("num:%d\n", i_array[index]);
    }*/
    system("pause");
    return 0;
}

 

posted @ 2014-02-02 00:17  Cephei  阅读(154)  评论(0)    收藏  举报