Search code examples
c++arraysbubble-sort

Bubble sort with array size


I want to do bubble sort for n elements of arraylist. Instead of declaring the arraylist first like below, I want to create the arraylist using for loops. So this is the code of declaring the arraylist first:

// A function to implement bubble sort  
void bubbleSort(int arr[], int n)  
{  
    int i, j;
    bool swapped; 
    int comparisons=0;
    for (i = 0; i < n-1; i++)  {
      swapped = false;
    // Last i elements are already in place  
    for (j = 0; j < n-i-1; j++)
    {
        comparisons++;
        if (arr[j] > arr[j+1])  
            {
                int temp = arr[j];
                arr[j]=arr[j+1];
                arr[j+1]=temp;
                swapped = true; 
            }
    }
    if (swapped == false) 
        break; 
    }   
    cout << "Number of comparisons = " << comparisons << endl;
}  

/* Function to print an array */
void printArray(int arr[], int size)  
{  
    int i;  
    for (i = 0; i < size; i++)  
        cout << arr[i] << " ";  
    cout << endl;  
}  

// Driver code  
int main()  
{  
    int arr[] = {1, 2, 3, 4, 5};  
    int n = 5;  
    bubbleSort(arr, n);  
    cout<<"Sorted array: \n";  
    printArray(arr, n);  
}  

which I do not want to do.

I have made this, but I do not know why it does not work. I'm still quite new with C++. May I know what's the problem. Thank you so much.

// A function to implement bubble sort  
void bubbleSort(int arr[], int n)  
{  
    int i, j;
    bool swapped; 
    int comparisons=0;
    for (i = 0; i < n-1; i++)  {
      swapped = false;
    // Last i elements are already in place  
    for (j = 0; j < n-i-1; j++)
    {
        comparisons++;
        if (arr[j] > arr[j+1])  
            {
                int temp = arr[j];
                arr[j]=arr[j+1];
                arr[j+1]=temp;
                swapped = true; 
            }
    }
    if (swapped == false) 
        break; 
    }   
    cout << "Number of comparisons = " << comparisons << endl;
}  

/* Function to print an array */
void printArray(int arr[], int size)  
{  
    int i;  
    for (i = 0; i < size; i++)  
        cout << arr[i] << " ";  
    cout << endl;  
}  


Solution

  • There are two problems:

    1. Arrays are 0-indexed.
    2. Variable length array which is not really legal in C++.

    So write main like:

    // Driver code  
    int main()  
    {  
        int n = 5;  
        int* arr = new int[n];
        for(int i=0; i<n; i++){
            arr[i]=i+1;
            cout<<arr[i];
            cout<<endl;
        }
        bubbleSort(arr, n);  
        cout<<"Sorted array: \n";  
        printArray(arr, n);
        delete[] arr;
    }