归并排序相关题目

//mergeSort:
void mergeSort(int* data, int length, int start, int end, int* tempArray){
    if (start == end){
        tempArray[start] = data[start];
        return;
    }
    int middle = (start + end) >> 1;
    mergeSort(data, length, start, middle, tempArray);
    mergeSort(data, length, middle + 1, end, tempArray);
    int index1 = start;
    int index2 = middle + 1;
    int indexTemp = start;
    while (index1 <= middle && index2 <= end){
        if (data[index1] < data[index2])
            tempArray[indexTemp++] = data[index1++];
        else
            tempArray[indexTemp++] = data[index2++];
    }
    while (index1 <= middle)
        tempArray[indexTemp++] = data[index1++];
    while (index2 <= end)
        tempArray[indexTemp++] = data[index2++];
    for (int i = start; i <= end; ++i){
        data[i] = tempArray[i];
    }
}
void mergeSortInterface(int* data, int length){
    if (data == nullptr || length <= 0)
        return;
    int* tempArray = new int[length];
    mergeSort(data, length, 0, length - 1, tempArray);
    delete[] tempArray;
}
//数组中的逆序对:利用归并排序思想,分治递归
void InversePairs(int* array, int length, int start, int end, int& count, int* tempArray){
    if (start == end){
        tempArray[start] = array[start];
        return;
    }
    int middle = (start + end) >> 1;
    InversePairs(array, length, start, middle, count, tempArray);
    InversePairs(array, length, middle + 1, end, count, tempArray);
    int index1 = middle;
    int index2 = end;
    int indexTemp = end;
    while (index1 >= start && index2 >= middle + 1){
        if (array[index1] > array[index2]){
            tempArray[indexTemp--] = array[index1--];
            count += index2 - middle;
        }
        else
            tempArray[indexTemp--] = array[index2--];
    }
    while (index1 >= start)
        tempArray[indexTemp--] = array[index1--];
    while (index2 >= middle + 1){
        tempArray[indexTemp--] = array[index2--];
    }
    for (int i = start; i <= end; i++)
        array[i] = tempArray[i];
}
int InversePairsInterface(int* array, int length){
    if (array == nullptr || length <= 0)
        return -1;
    int count = 0;
    int* tempArray = new int[length];
    InversePairs(array, length, 0, length - 1, count, tempArray);
    delete[] tempArray;
    return count;
}
posted @ 2017-08-27 23:06  sold_out  阅读(313)  评论(0编辑  收藏  举报