gpt4 book ai didi

c++ - 如何在 C++ 中用数组和指针实现插入排序算法?

转载 作者:太空狗 更新时间:2023-10-29 23:44:34 27 4
gpt4 key购买 nike

我正在尝试学习 C++、数组和指针。我决定实现 insertion sort algorithm .所以,这是我的代码和错误的输出。我应该怎么做才能纠正它?你能告诉我我的错误是什么吗?如果是常见错误,我应该避免什么?

我的代码:

// InsertionSort.cpp

#include "stdafx.h"
#include <iostream>

int DeclareAnInteger();
int* DeclareAndShowTheArray(int n);
int* InsertionSort(int *A, int n);

int main()
{

int n = DeclareAnInteger();
int *A;
A = DeclareAndShowTheArray(n);
int *B;
B = InsertionSort(A, n);

system("PAUSE");
return 0;
}

int DeclareAnInteger()
{
int n;
std::cout << "Please enter a positive integer n: ";
std::cin >> n;
return n;
}

int* DeclareAndShowTheArray(int n)
{
int *A;
A = (int *)alloca(sizeof(int) * n);
for (int i = 0; i < n; i++)
{
std::cout << "Please enter the value of A[" << i + 1 << "]: ";
std::cin >> A[i];
}
std::cout << "The unsorted array is: ";
for (int i = 0; i < n; i++)
{
std::cout << A[i];
std::cout << "\t";
}
std::cout << "\n";
return A;
}

int* InsertionSort(int *A, int n)
{
int k;
//int *A = new int[n];
for (k = 1; k < n; k++)
{
int key = A[k];
int m = k - 1;
while (m >= 0 & A[m] > key)
{
A[m + 1] = A[m];
m = m - 1;
}
A[m + 1] = key;
}
std::cout << "The sorted array is: ";
for (int i = 0; i < n; i++)
{
std::cout << A[i];
std::cout << "\t";
}
std::cout << "\n" << std::endl;
return A;
}

我的输出: enter image description here

最佳答案

这是个大问题:

A = (int *)alloca(sizeof(int) * n);

alloca 函数在堆栈上分配,当函数返回时它会丢失,给你一个杂散指针和undefined behavior当您取消引用此指针时。

如果您正在编写 C++,则使用 new,如果您编写 C,则使用 malloc

关于c++ - 如何在 C++ 中用数组和指针实现插入排序算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28002098/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com