Sorting problems
 CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com

# Thread: Sorting problems

1. Junior Member
Join Date
Aug 2012
Posts
4

## 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;
}

2. ZuK
Senior Member
Join Date
Oct 2002
Location
Austria
Posts
1,284

## Re: Sorting problems

You have bufferoverflows in your bubblesort.
And please use CODE tags when posting code.
Kurt

3. Junior Member
Join Date
Aug 2012
Posts
4

## Re: Sorting problems

Thanks Kurt! Can you be more specific?

4. Elite Member Power Poster
Join Date
Apr 1999
Posts
27,449

## Re: Sorting problems

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

5. Junior Member
Join Date
Aug 2012
Posts
4

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

6. Junior Member
Join Date
Aug 2012
Posts
4

## Re: Sorting problems

I mean:

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

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

Click Here to Expand Forum to Full Width