[英]Merging two sorted arrays with for loop
我有一個函數,將兩個排序數組合並為一個,並返回指向它的指針。 我想使用一個for循環,而不是一會兒。 但是,在某些測試用例中,合並數組的最后1個或2個元素不在原處。 如果有人可以幫助解決此問題並保持for循環,我將不勝感激。
int * mergeSort(int arr1[], int arr2[],int len)
{
/* len is the combined length of the two arrays */
static int sorted[100];
int pos1=0, pos2=0;
for (int i=0; i<len; i++)
{
if (arr1[pos1]<=arr2[pos2])
{
sorted[i]=arr1[pos1];
pos1++;
}
else
{
sorted[i]=arr2[pos2];
pos2++;
}
}
return sorted;
}
您的問題是您似乎無法處理超出輸入數組末尾的情況。 如果存在未初始化的內存-您將獲得未定義的行為。
您可以通過用定點值終止數組來避免這種情況,例如INT_MAX
,該值應始終大於數組中所有可能的值:
int a[] = { 1, 2, 104, INT_MAX};
int b[] = { 101, 102, 105, INT_MAX};
int* ptr = mergeSort(a,b,6);
for(int i = 0; i < 6; i++){
cout << i << " " << ptr[i] << endl;
}
或者,您可以傳遞兩個數組的實際長度並正確處理它們:
int * mergeSort(int arr1[], int len1, int arr2[],int len2)
{
/* len is the combined length of the two arrays */
static int sorted[100];
int pos1=0, pos2=0;
for (int i=0; i< len1 + len2; i++)
{
if ((pos2 == len2) || (arr1[pos1] <= arr2[pos2] && (pos1 < len1)))
{
sorted[i]=arr1[pos1];
pos1++;
}
else
{
sorted[i]=arr2[pos2];
pos2++;
}
}
return sorted;
}
這不會回答您的代碼有什么問題,但是為了回答如何合並兩個排序范圍的問題,我建議使用std::merge
:
int * mergeSort(int arr1[], int arr2[], int len1, int len2)
{
//I am not condoning the use of a static buffer here,
//I would probably use a std::vector or std::array,
//possibly a boost::static_vector if really necessary
static int sorted[100];
std::merge(arr1, arr1 + len1, arr2, arr2 + len2, sorted);
return sorted;
}
我還將int len
更改為int len1, int len2
因為您需要知道各個數組的長度,而不僅僅是它們的組合長度,以避免讀取輸入數組的末尾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.