Reputation: 41
#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
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
Reputation: 4663
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