# Sorting problems

• August 29th, 2012, 03:56 PM
rocketjumper
Sorting problems
HI I just started learning c++. Below is the bubble_sorting program I wrote. Complied no error under eclipse(Ubuntu). But the result is not right.

What is happening is, no matter what input numbers I provided, after sorting, the smallest number would be set to zero. Please, can anyone point out where did I do wrong. Many thanks in advance!

//start of the program
//Bubble_sorting

#include <iostream>
using namespace std;

void BubbleSort(int *list,int len)
{
int i,j,temp;
for(i=0;i<len;i++)
for(j=0;j<len-i;j++)
{
if(list[j]>list[j+1])
{
temp=list[j];
list[j]=list[j+1];
list[j+1]=temp;
}
}
}

int main ()
{
int len;
cout<<"input the number of int to sort"<<endl;
cin>>len;
int *p = new int[len];

cout<<"Input ten number:";
for(int i=0;i<len;i++)
cin>>p[i];
cout<<endl;

cout<<"Before sorting: ";
for(int i=0;i<len;i++)
cout<<p[i]<<" ";
cout<<endl;

BubbleSort(p,len);
cout<<"After sorting: ";
for(int i=0;i<len;i++)
cout<<p[i]<<" ";

cout<<endl;
cout<<p[0]<<endl;
cout<<endl;

delete[] p;
p = NULL;
return 0;
}
• August 29th, 2012, 04:04 PM
ZuK
Re: Sorting problems
You have bufferoverflows in your bubblesort.
And please use CODE tags when posting code.
Kurt
• August 29th, 2012, 04:12 PM
rocketjumper
Re: Sorting problems
Thanks Kurt! Can you be more specific?
• August 29th, 2012, 04:32 PM
Paul McKenzie
Re: Sorting problems
Quote:

Originally Posted by rocketjumper
Thanks Kurt! Can you be more specific?

Code:

`for(j=0;j < len-i;j++ )`
Assume len is 10 and i happens to be 0. That loop translates to this:
Code:

`for(j=0;j < 10; j++)`
So you will loop from 0 to 9. But your code has this:
Code:

`if( list[j] > list[j+1])`
Which translates to this on the last iteration of the loop
Code:

`if (list [9] > list[10])`
Do you see a problem? You're accessing an invalid array element (list[10]).

Regards,

Paul McKenzie
• August 29th, 2012, 04:39 PM
rocketjumper
Re: Sorting problems
Thanks Paul! That makes sense now! Just modify the inner for loop as

Code:

`for(j=0;j<len-i;j++)`
will solve the problem! Thanks for explaining this to me
• August 29th, 2012, 04:41 PM
rocketjumper
Re: Sorting problems
I mean:

Code:

`for(j=0;j<len-i-1;j++)`