[英]Main skipping over function?
我正在嘗試通過一個免費的在線課程來教自己算法和數據結構的基礎知識,因此,盡管它是合並排序方面的第一手資料。 這實際上並不會用於任何東西,所以它很草率,但是我似乎遇到了一個問題,即main不調用MergeSort函數。
輸出為00000000,(我假設因為數組從未分配任何東西)。 當我通過gdb運行程序時,程序似乎到達那一行,然后完全跳過該函數,直接進入打印數組的循環。
有什么想法嗎? 我想念一些愚蠢的東西嗎?
#include <iostream>
using namespace std;
int *MergeSort(int array[], int sizeOf);
int main(){
int numbers[8] = {5, 4, 1, 8, 7, 2, 6, 3};
int *array = MergeSort(numbers, 8);
for (int i = 0; i < 8; i++)
cout << array[i];
return 0;
}
int *MergeSort(int array[], int sizeOf){
int *leftArr = new int[sizeOf/2]; // Build arrays to split in half
int *rightArr = new int[sizeOf/2];
if (sizeOf < 2){ // Base case to end recursion
return array;
}
else{
for (int i = 0; i < (sizeOf/2); i++){ // Left gets first half
leftArr[i] = array[i];
}
int j = (sizeOf/2) - 1; // Set point to start building 2nd
for (int i = sizeOf; i >= (sizeOf/2); i--){
rightArr[j] = array[i]; // Build other half of array
j--;
}
leftArr = MergeSort(leftArr, sizeOf/2); // Call Recursive functions
rightArr = MergeSort(rightArr, sizeOf/2);
}
static int *newArray = new int[sizeOf]; // Sorted array to Build
int k = 0; // Iterators to build sorted func
int m = 0;
int p = 0;
while (p < sizeOf){
if (leftArr[k] < rightArr[m]){ // Left Arr's current value is less
newArray[p] = leftArr[k]; // right arr's current calue
k++;
}
else if (leftArr[k] >= rightArr[m]){
newArray[p] = rightArr[k];
m++;
}
p++;
}
//for (int i = 0; i < 8; i++)
// cout << newArray[i] << endl;
return newArray; // Return address to new array
}
MergeSort()
存在一個基本的設計問題:
static
newArray
。 這意味着所有調用都使用同一靜態變量的相同實例(並覆蓋遞歸調用返回的實例)。 您需要通過使newArray為非靜態來解決此問題。 並且在函數的最后,您需要delete[]
遞歸調用返回的數組,以避免內存泄漏。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.