所以有我的代码,当我运行它时,我的内存已经耗尽 它可能取决于我的电脑或它的代码问题? 合并排序算法我在几个站点读过,但没什么帮助
#include <iostream>
using namespace std;
int quicksort (int m[], int left, int right)
{
int i = left;
int j = right;
int middle = m[(left + right) / 2];
do{
while (m[i] <= middle)
i++;
while (m[j] >= middle)
j--;
if (i <= j)
{
if (m[i] > m[j])
swap (m[i], m[j]);
i++;
j--;
}
}while (i <= j);
if (left < j)
quicksort (m, left, j);
if (i < right)
quicksort (m, i, right);
}
int main ()
{
int n, i;
cin>> n;
int m[n];
for (i = 0; i <= n; i++)
cin >> m[i];
quicksort (m , 0, n - 1);
for (i = 0; i <= n; i++)
cout << m[i] << " ";
}
答案 0 :(得分:1)
所以它现在应该可以工作了,你超越了数组的范围。
#include <iostream>
using namespace std;
int quicksort (int m[], int left, int right)
{
int i = left;
int j = right;
int middle = m[(left + right) / 2];
do{
while (m[i] < middle)
i++;
while (m[j] > middle)
j--;
if (i <= j)
if (m[i] > m[j])
swap (m[i], m[j]);
i++;
j--;
}
}while (i <= j);
if (left < j)
quicksort (m, left, j);
if (i < right)
quicksort (m, i, right);
}
int main () {
int n, i;
cin>> n;
int m[n + 1];
for (i = 0; i < n; i++){cin >> m[i];}
quicksort (m , 0, n - 1);
for (i = 0; i < n; i++){cout << m[i] << " ";}
}