打印输出数组

时间:2019-09-29 09:32:08

标签: c++ malloc quicksort dev-c++

我正在尝试为快速排序算法编写C ++代码。我正在使用指针(*arr)存储整数输入数组。在调用main()之后的quickSort()函数中,for循环打印排序后的数组。

在输出中,打印了排序后的数组,但是程序等待了几秒钟,然后说:“ 进程在19.07秒后退出,返回值为3221226356

是因为malloc()吗?

#include<bits/stdc++.h>
using namespace std;
void swap(int *arr,int a,int b)
{
    int temp=*(arr+a);
    *(arr+a)=*(arr+b);
    *(arr+b)=temp;

}
int partition(int *arr,int n,int low,int high)
{
    int i,pivot;
    i=low-1;
    pivot=*(arr+high);
    for(int j=low;j<=high-1;j++)
    {
        if(*(arr+j)<pivot)
        {
            i++;
            swap(arr,i,j);
        }
    }

    swap(arr,i+1,high);
    return i+1;

}
void quickSort(int *arr,int n,int low,int high)
{
    if(low<high)
    {
        int pos;
        pos=partition(arr,n,low,high);
        cout<<"Partition for pos:"<<pos<<" ";
        for(int i=0;i<n;i++)
        {
            cout<<*(arr+i)<<" ";
        }
        cout<<endl;
        quickSort(arr,n,low,pos-1);
        quickSort(arr,n,pos+1,high);

    }
}
int main()
{
    int n,*arr;
    arr=(int*)malloc(n*sizeof(int));
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cout<<"Enter"<<endl;
        cin>>*(arr+i);
    }

    quickSort(arr,n,0,n-1);

    for(int i=0;i<n;i++)
    {
        cout<<*(arr+i)<<" ";
    }
    return 0;
}

n = 7的输出和输入数组{10,80,30,90,40,50,70}:

7
Enter
10
Enter
80
Enter
30
Enter
90
Enter
40
Enter
50
Enter
70
Partition for pos:4 10 30 40 50 70 90 80
Partition for pos:3 10 30 40 50 70 90 80
Partition for pos:2 10 30 40 50 70 90 80
Partition for pos:1 10 30 40 50 70 90 80
Partition for pos:5 10 30 40 50 70 80 90
10 30 40 50 70 80 90
--------------------------------
Process exited after 19.07 seconds with return value 3221226356
Press any key to continue . . .

0 个答案:

没有答案