归并+二分

 
递归二分
 
#include <iostream>
using namespace std;
int a[10]={1,4,6,8,7,3,2,9,5,10};
void MergeSort(int a[], int n);
void MSort(int a[], int TmpA[], int L, int RightEnd);
void Merge(int a[], int TmpA[], int L, int R, int RightEnd);
int BinarySearch(int a[], int Start, int End, int key);
int main()
{
    MergeSort(a, 10);
    //for(int i=0;i<10;i++)
    //cout << a[i] << endl;
    cout << BinarySearch(a, 0, 9, 4);
}

void MergeSort(int a[], int n)
{
    int TmpA[10];
    MSort(a, TmpA, 0, 9);
}

void MSort(int a[], int TmpA[], int L, int RightEnd)
{
    int Center;
    if(L<RightEnd)
    {
        Center=(L+RightEnd)/2;
        MSort(a, TmpA, L, Center);
        MSort(a, TmpA, Center+1, RightEnd);
        Merge(a, TmpA, L, Center+1, RightEnd);
    }
}

int BinarySearch(int a[], int Start, int End, int key)
{
    int Center=(Start+End)/2;
    if(Start>End)
    return 0;
    if(a[Center]<key)
    return BinarySearch(a, Center+1, End, key);
    else if(a[Center]>key)
    return BinarySearch(a, Start, Center-1, key);
    else return Center+1;
}

void Merge(int a[], int TmpA[],int L, int R, int RightEnd)
{
    int LeftEnd=R-1;
    int Tmp = L;
    int NumElements = RightEnd-L+1;
    while(L<=LeftEnd&&R<=RightEnd)
    {
        if(a[L]<=a[R])
        TmpA[Tmp++]=a[L++];
        else 
        TmpA[Tmp++]=a[R++];
    }
    while(L<=LeftEnd)
    TmpA[Tmp++]=a[L++];
    while(R<=RightEnd)
    TmpA[Tmp++]=a[R++];
    for(int i=0;i<RightEnd;i++)
    a[i]=TmpA[i];
}
View Code

 

 

posted @ 2018-12-30 21:05  贾铭梓  阅读(194)  评论(0编辑  收藏  举报