mardi 15 décembre 2015

Bubble sort method for array with random size

I am trying to use bubble sort method for array with random size. Here's the code:

#include <iostream>

using namespace std;

int main()
{
    int n;
    cout<<"Enter n";
    cin>>n;
    int arr[n],swap;
    cout<<"Enter number"<<endl;
    cin>>arr[n];
    for(int i=0;i<n-1;i++)
    for(int j=0;i<n-i-1;j++)
        if(arr[j]>arr[j+1])
    {
        swap=arr[j];
        arr[j]=arr[j+1];
        arr[j+1]=swap;
    }
    for(int k=0;k<n;k++)
        cout<<"arr["<<k<<"]="<<arr[k]<<endl;
    return 0;
}

When I define the elements of the array in this way the program works:

const n=5;
int arr[n]={1,2,3,4,5)

But I need to enter the size of the array (n) and its elements from the keyboard. But when I run my code the program crashes after I enter the first number. Is there a way to fix it?




Aucun commentaire:

Enregistrer un commentaire