C++ c++;溢出、合并排序、反转计算器
我的代码是计算数组中的反转数。计算很顺利。 问题是,通常unsigned int的范围是4294967295,但它只接受2147483647的范围,等价地,它不识别unsigned数据类型,而是接受它为signedC++ c++;溢出、合并排序、反转计算器,c++,sorting,merge,inversion,C++,Sorting,Merge,Inversion,我的代码是计算数组中的反转数。计算很顺利。 问题是,通常unsigned int的范围是4294967295,但它只接受2147483647的范围,等价地,它不识别unsigned数据类型,而是接受它为signed unsigned int _mergeSort(int arr[], int temp[], unsigned int left, unsigned int right); unsigned int merge(int arr[], int temp[], unsigned int
unsigned int _mergeSort(int arr[], int temp[], unsigned int left, unsigned int right);
unsigned int merge(int arr[], int temp[], unsigned int left, unsigned int mid, unsigned int right);
unsigned int mergeSort(int arr[], int array_size) {
int *temp = (int *)malloc(sizeof(int)*array_size);
return _mergeSort(arr, temp, 0, array_size - 1);
}
unsigned int _mergeSort(int arr[], int temp[], unsigned int left, unsigned int right) {
unsigned int mid;
unsigned int inv_count = 0;
if (right > left) {
mid = (right + left) / 2;
inv_count = _mergeSort(arr, temp, left, mid);
inv_count += _mergeSort(arr, temp, mid + 1, right);
inv_count += merge(arr, temp, left, mid + 1, right);
}
return inv_count;
}
unsigned int merge(int arr[], int temp[], unsigned int left, unsigned int mid, unsigned int right) {
unsigned int i, j, k;
unsigned int inv_count = 0;
i = left;
j = mid;
k = left;
while ((i <= mid - 1) && (j <= right)) {
if (arr[i] <= arr[j]) {
temp[k++] = arr[i++];
} else {
temp[k++] = arr[j++];
inv_count = inv_count + (mid - i);
}
}
while (i <= mid - 1)
temp[k++] = arr[i++];
while (j <= right)
temp[k++] = arr[j++];
for (i = left; i <= right; i++)
arr[i] = temp[i];
return inv_count;
}
int main(int argv, char** args) {
const int size = 100000;
int arr[size];
unsigned int i = 0;
int converted;
string input;
fstream dataFile("IntegerArray.txt", ios::in);
if (dataFile) {
getline(dataFile, input);
while (dataFile) {
converted = atoi(input.c_str());
arr[i++] = converted;
getline(dataFile, input);
}
dataFile.close();
} else {
cout << "error" << endl;
}
printf("Number of inversions are %d \n", mergeSort(arr, i));
getchar();
return 0;
}
unsigned int\u mergeSort(int arr[],int temp[],unsigned int left,unsigned int right);
无符号整数合并(整数arr[],整数temp[],无符号整数左,无符号整数中,无符号整数右);
无符号整数合并排序(整数arr[],整数数组大小){
int*temp=(int*)malloc(sizeof(int)*数组大小);
返回合并排序(arr,temp,0,数组大小-1);
}
无符号整数合并排序(整数arr[],整数temp[],左无符号整数,右无符号整数){
无符号整数mid;
无符号整数库存计数=0;
如果(右>左){
中间=(右+左)/2;
库存计数=\u合并排序(arr、temp、left、mid);
库存计数+=\u合并排序(arr、temp、mid+1,右);
库存计数+=合并(arr、temp、左、中+1、右);
}
返回存货盘点;
}
无符号整数合并(整数arr[],整数temp[],无符号整数左,无符号整数中,无符号整数右){
无符号整数i,j,k;
无符号整数库存计数=0;
i=左;
j=中等;
k=左;
而((i在调用printf()
时,您使用的格式说明符是%d
,意思是有符号整数。传递的实际值是无符号整数,正确的格式说明符是%u
。修复printf()
调用并再次测试
如果您发布错误,我可能会有所帮助。没有错误。数字溢出,因此返回负数。.以下划线开头的名称,如\u mergeSort
,保留在全局命名空间中。一些一般准则:使用有符号整数表示数字,使用标准库集合,如std::vector
I除了动态分配原始数组外,不要使用 MalOC 用于C++代码中的分配,不要在程序结束时添加“等待”(只需让IDE执行任何等待,或者从命令解释器运行),请您具体说明这个问题,我尝试过U,X,O,但仍然是相同的输出。但是谢谢您的好信息。