Search code examples
c++arrayssortingbubble-sort

Bubble sort method for array with dynamically determined size


I am trying to use bubble sort method for array with dynamically determined 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?


Solution

  • #include <iostream>
    #include <vector>
    
    using namespace std;
    
    int main()
    {
        int n, swap, temp;
        vector<int> arr;
        cout<<"Enter n";
        cin>>n;
    
        // Loop and accept the n values.
        // You may need to take care of the new line.
        for(int i = 0; i < n; ++i)
        {
            cout << "Enter a number : ";
            cin >> temp;
            arr.push_back(temp);
        }
    
        for(int i=0;i<n-1;i++)
        for(int j=0;j<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;
    }
    

    Notice how a loop is used to extract n values from user. Also using a std::vector relieves you from writing code for a runtime sized array with new and delete.

    Also, you inner loop was checking i<n-i-1 and incrementing j which should be j<n-i-1 instead, otherwise j will increment indefinitely till INT_MAX.