Suman Saurabh
Suman Saurabh

Reputation: 41

My Bubble Sort Program worked for one case but not for other. How this is Possible?

#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,

Upvotes: 0

Views: 58

Answers (2)

Leal Li
Leal Li

Reputation: 257

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>

Upvotes: 0

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.

Upvotes: 1

Related Questions