Bubble Sorting Problem

This is a discussion on Bubble Sorting Problem within the C Programming forums, part of the General Programming Boards category; Hi Guys its me again... Password program was our first lesson now to our second topic the bubble sort technique... ...

1. 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... ^^

2. 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! >

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!

3. 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

4. Originally Posted by 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
Your compiler is being very extra nice to you. In a 30 element array in C, there *IS* no temp[30].

In C, temp[30] array runs only from temp[0] through temp[29].

Load up a lot of other programs in memory and it should crash the program. You aren't getting any warnings from the compiler?