简体   繁体   English

如何按升序对动态数组排序?

[英]How do I sort a dynamic array in ascending order?

I have an assignment to have a user enter two number which are the size of the arrays then enter the elements for the arrays. 我的任务是让用户输入两个数字,它们分别是数组的大小,然后输入数组的元素。 Then I have to combine them into one array and sort them in ascending order. 然后,我必须将它们组合成一个数组并按升序对其进行排序。 The catch is I have to do it with only dynamic arrays. 要注意的是,我只能使用动态数组来做到这一点。 I already combined the arrays and tried to sort them but it crashes every time on that part. 我已经组合了数组并试图对其进行排序,但是每次在那部分都崩溃。 This is my code to sort the array: 这是我对数组进行排序的代码:

int *temp;
temp = &array1size;
for (int i = 0; i < *size1ptr; i++)
{

    for (int j = 0; j < *size1ptr - 1; j++)
    {
        if (*(finalarray + j) > *(finalarray + j + 1))
        {

            temp = &*(finalarray + j);
            *(finalarray + j) = *(finalarray + j + 1);
            *(finalarray + j + 1) = *temp;

        }
    }/*End inner for loop*/
}/*End outer for loop*/

IT crashes on this part and I cant figure out why. IT崩溃了,我不知道为什么。 Here is some other code where I make the other arrays: 这是我制作其他数组的其他代码:

int array1size, array2size;
int *array1ptr, *array2ptr, *size1ptr, *size2ptr, *finalarray, *finalptr;

cout << "enter size of first array: ";
cin >> array1size;
size1ptr = &array1size;
array1ptr = new int[*size1ptr];

cout << "Enter array content: ";
for (int i = 0; i < *size1ptr; i++)
{
    cin >> *(array1ptr + i);
}

cout << "enter size of second array: ";
cin >> array2size;
size2ptr = &array2size;
array2ptr = new int[array2size];

cout << "Enter array content: ";
for (int i = 0; i < *size2ptr; i++)
{
    cin >> *(array2ptr + i);
}

finalarray = new int[*size1ptr];

for (int i = 0; i < *size1ptr; i++)
{
    *(finalarray + i) = *(array1ptr + i);
}
for (int i = 0; i < *size2ptr; i++)
{

    *size1ptr += 1;
    *(finalarray + *size1ptr - 1) = *(array2ptr + i);

}

As mentioned in my comment, you CANNOT dynamically grow the size of C-style arrays (use std::vector if you are willing to achieve that) 如我的评论中所述,您不能动态增加C样式数组的大小(如果愿意,请使用std :: vector

In your case, you need to give the final size (sum of size of array1 and array2) of the final array at the time of creation, ie, 在您的情况下,您需要在创建时提供最终数组的最终大小(array1和array2的总和),即

finalarray = new int[*size1ptr + *size2ptr];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM