0
#include<iostream>
using namespace std;
int main(){
    int n;
    cout<<"Enter size of array-";
    cin>>n;
    int arr[n];
    cout<<"Enter all elements"<<endl;
    for(int i=0;i<n;i++){
        cin>>arr[i];
    }
    cout<<"Your Entered elements are"<<endl;
    for(int i=0;i<n;i++){
        cout<<arr[i]<<",";
    }
    cout<<endl;
    for(int x=0;0<n-x;x++){
        for(int i=0;i<n;i++){
            if(arr[i]>arr[i+1]){
                int tem=arr[i];
                arr[i]=arr[i+1];
                arr[i+1]=tem;
            }
        }
    }
    cout<<"Sorted Array"<<endl;
    for(int i=0;i<n;i++){
        cout<<arr[i]<<",";
    }
    return 0;
}

For first case Enter size of array-6 Enter all elements 4 5 3 2 1 9 Your Entered elements are 4,5,3,2,1,9, Sorted Array 1,2,3,4,5,9, For second case(This have Problem) Enter size of array-4 Enter all elements 20 40 30 50 Your Entered elements are 20,40,30,50,

  • 2
    Your program has undefined behaviour due to accessing `arr[n]` on the last iteration of the inner loop. In any case `int arr[n];` is VLA, [which isn't part of C++](https://stackoverflow.com/questions/1887097) and a ticking time bomb. – Lukas-T Nov 19 '21 at 08:42

2 Answers2

1

You are trying to access arr[i+1]. When i = n-1, arr[i+1] = arr[n], so your access is out-of-bounds.

Also, int arr[n] isn't valid C++. You should use std::vector<int> instead.

0
Bubble sort,you should
<code>
 for (var i = 0; i < len - 1; i++) {
        for (var j = 0; j < len - 1 - i; j++) {
            if (arr[j] > arr[j+1]) {      
                var temp = arr[j+1];       
                arr[j+1] = arr[j];
                arr[j] = temp;
            }
        }
    }
</code>
Leal Li
  • 247
  • 1
  • 2
  • 10