Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 136,583 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,934 people online right now. Registration is fast and FREE... Join Now!




bubble sort

 
Reply to this topicStart new topic

bubble sort

ratul majumdar
27 Sep, 2008 - 08:21 AM
Post #1

New D.I.C Head
*

Joined: 27 Sep, 2008
Posts: 1

cpp

#include<stdio.h>
#include<conio.h>
#define SIZE 80
void main()
{
int a[SIZE],i,temp,j,n;
printf("enter the size:",n);
scanf("%d",&n);
printf("enter the nos.");
for(i=0;i<n;i++)
{
printf("a[%d]:",i);
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[i+j])
{
temp=a[i];
a[i]=a[i+j];
a[i+j]=temp;
}
}
}
printf("the result is:");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
getch();
}

*edit: Please use code tags in the future, thanks! And also include an actual question, it may help. code.gif

This post has been edited by Martyr2: 27 Sep, 2008 - 09:49 AM
User is offlineProfile CardPM
+Quote Post

Martyr2
RE: Bubble Sort
27 Sep, 2008 - 10:17 AM
Post #2

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 5,213



Thanked: 217 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
You had a few issues with formatting and making it nice to even enter numbers. You also had some of your loops a bit off with their counters etc. Here is your code with a few tweaks to make it work a bit nicer...

cpp

#include<stdio.h>
#include<conio.h>
#define SIZE 80

void main()
{
int a[SIZE],i,temp,j,n;
printf("enter the size: ");
scanf("%d",&n);
printf("enter the nos.\n");

for(i=0;i<n;i++)
{
printf("Number: ");
scanf("%d",&a[i]);
printf("a[%d] = %d\n",i, a[i]);
}

for(i=0;i<n-1;i++)
{
// We want to make sure that J always starts at 0 but subtracts
// i (the last value bubbled)
for(j=0;j<n-1-i;j++)
{
// Notice here that we use j + 1 not + i
if(a[j]>a[j + 1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}

}

printf("the result is:\n");

for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
getch();
}


Normally I wouldn't setup a bubblesort like this, but I just figured I would show you the error of your ways and let you handle it from there. The way I like to do it is with bubbling to the end of the array and using a flag to let you know if any swaps have been made. It makes the sort a bit more efficient, especially for arrays that are close to being sorted.

Enjoy!

"At DIC we be messed up bubble sorting code ninjas... deformed bubble sorting perhaps? Interesting." decap.gif
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/3/08 12:43AM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month