# Bubble Sorting Problem

• 12-02-2009
jappy512
Bubble Sorting Problem
Hi Guys its me again... Password program was our first lesson now to our second topic the bubble sort technique... hmmm... I had already the program.

Code:

```#include <stdio.h> #include <string.h> main() { int x, y; char name[5][30]; char temp[30]; clrscr(); printf("Enter 5 Student Names: \n"); for(x=1;x<=5;x++)  {  gets(name[x]);  }   for(x=4;x>=1;x--)   {   for(y=1;y<=x;y++)   {   if(strcmp(name[x],name[x+1])>0)     {     strcpy(temp,name[x]);     strcpy(name[x],name[x+1]);     strcpy(name[x+1],temp);     }   }   } printf("Names in Alphabetical Order:\n"); for(x=1;x<=5;x++) printf("%s\n",name[x]); getche(); }```
The program runs and here is the result when I enter 5 names:

Enter 5 Student Names:
Not2x
Ron2x
Ton2x
Mai2x
Don2x
//The result
Names in Alphabetical Order:
Mai2x
Not2x
Ron2x
Ton2x
No2x<<--- repeats itself in sort

What could be the problem with my codes? Thanks in advance guys... ^^
• 12-02-2009
Your program is taking in *ONE* name, and then sorting the entire array of names.

That's a waste. You're doing one sort of the array, for EVERY SINGLE entered name. <eek!>

< iMalc will be in a tizzy! > :p

First, in one loop, take in *ALL* the names

THEN sort it one time, in a second nested loop.

Now, as to your sorting code - it's running out of bounds! X starts at 4, but inside the inner loop, you reference "x + 1".

An array of 5 names doesn't have array[5]. Also, what about array[0]? It's being skipped.

Horror!
• 12-02-2009
jappy512
Thanks a lot adak for immediate reply... well i just replace temp with temp[30]... and it works fine now..... I'm still new on this one... hahaha... I've learned a lot... Thank you
• 12-02-2009