#include <iostream> using namespace std; const int LENGTH = 100; int temp[LENGTH]; int count = 0; void Merge(int array[], int low, int mid, int high); void MergeSort(int array[], int low, int high); /** * 合并两个数组[low, mid],(mid, high]到数组[low, high] * @param array 待排序数组 * @param low 起始下标 * @param mid 分界线 * @param high 终止下标 */ void Merge(int array[], int low, int mid, int high) { int tempIndex = low; int leftIndex = low; int rightIndex = mid + 1; while(leftIndex <= mid && rightIndex <= high) { if(array[leftIndex] < array[rightIndex]) { temp[tempIndex++] = array[leftIndex++]; } else // array[rightIndex]要比[leftIndex, mid]的元素都小,逆序对由此产生 { temp[tempIndex++] = array[rightIndex++]; count += (mid - leftIndex + 1); } } while(leftIndex <= mid) { temp[tempIndex++] = array[leftIndex++]; } while(rightIndex <= high) { temp[tempIndex++] = array[rightIndex++]; } for(int i = low; i <= high; ++i) { array[i] = temp[i]; } } void MergeSort(int array[], int low, int high) { if(low == high) return; int mid = (low + high) / 2; MergeSort(array, low, mid); MergeSort(array, mid + 1, high); Merge(array, low, mid, high); } int main() { int array[] = {0, 4, 2, 6, 12, 10, 8, 7, 5}; MergeSort(array, 0, 8); for(auto val : array) { cout << val << " "; } cout << endl; cout << "--------------------------" << endl; cout << count << endl; return 0; }
说明:需要编译器支持C++11
PS C:\Users\Administrator\Desktop\codes> g++ -o .\InverseNumber.exe .\InverseNumber.cpp -std=c++11 PS C:\Users\Administrator\Desktop\codes> .\InverseNumber.exe 0 2 4 5 6 7 8 10 12 -------------------------- 12 PS C:\Users\Administrator\Desktop\codes> g++ -v Using built-in specs. COLLECT_GCC=F:\GreenSoftware\CodeBlocks\TDM-GCC\bin\g++.exe COLLECT_LTO_WRAPPER=F:/GreenSoftware/CodeBlocks/TDM-GCC/bin/../libexec/gcc/mingw32/5.1.0/lto-wrapper.exe Target: mingw32 Configured with: ../../../src/gcc-5.1.0/configure --build=mingw32 --enable-languages=ada,c,c++,fortran,lto,objc,obj-c++ --enable-libgomp --enable-lto --enable-graphite --enable-libstdcxx-debug --enable-threads=posix --enable-version-specifi c-runtime-libs --enable-fully-dynamic-string --enable-libstdcxx-threads --enable-libstdcxx-time --with-gnu-ld --disable- werror --disable-nls --disable-win32-registry --disable-symvers --enable-cxx-flags=‘-fno-function-sections -fno-data-sec tions -DWINPTHREAD_STATIC‘ --prefix=/mingw32tdm --with-local-prefix=/mingw32tdm --with-pkgversion=tdm-1 --enable-sjlj-ex ceptions --with-bugurl=http://tdm-gcc.tdragon.net/bugs Thread model: posix gcc version 5.1.0 (tdm-1) PS C:\Users\Administrator\Desktop\codes>
时间: 2024-10-08 10:13:24