Hi! I'm attempting to create a bubble sort. By the way: a bubble sort is essentially 2 linear sorts at the same time, right?
So far I've:
1) Created a list of random numbers in an array
2) Performed a linear sort from the beginning forward and the ending backward (at the same time)
3) Set it up in a loop that's SUPPOSED to continue looping until each half is sorted. Any time a swap is performed, a flag is enabled that continues the loop. If the flag is not enabled, the program falls out of the loop (ie: stops sorting). This is the part I'm having trouble with. The flag seems to work correctly, but it doesn't break the loop.
I haven't provided for numbers that are in the second half that belong in the first half (yet), but I'll get to that...
Also I probably have a lot of redundant code since I'm still trying to make it work... ;-)
Anyway, does anyone know why the WHILE condition is not being met?
Code:
#include<stdio.h>
#include<stdlib.h>
/*
this generates random numbers and sorts them
*/
//prototypes
void sort_main (void);
int main (void)
{
sort_main ();
return 0;
}
void sort_main (void)
{
int array[10];
int loop = 0;
int count = 0;
int max = 9;
int temp;
char cont = 'y';
//open output file for write
FILE *fp = fopen ("bubble_sort.txt", "w");
fprintf (fp,"Before:\n");
//initialize array values
for (loop = 0; loop <= max; loop++)
{
array[loop] = rand();
fprintf (fp,"\t%d", array[loop]);
}
fprintf (fp,"\n\nAfter:\n");
//check middle element if the number of elements is odd
if ((max + 1) % 2 != 0)
{
if (array[(max + 1) / 2] > array[(max + 1) / 2 + 1])
{
temp = array[(max + 1) / 2];
array[(max + 1) / 2 + 1] = array[max / 2];
array[(max + 1) / 2] = temp;
temp = 0;
}
}
do
{
cont = 'n';
for (loop = 0; loop < (max / 2); loop++)
{
//check from forward direction
if (array[loop] > array[loop + 1])
{
temp = array[loop + 1];
array[loop + 1] = array[loop];
array[loop] = temp;
temp = 0;
cont = 'y';
}
else if (array[loop] == array[loop + 1])
{
array[loop + 1] = 0;
cont = 'y';
}
//check from reverse direction
if (array[max - loop] < array[max - (loop + 1)])
{
temp = array[max - (loop + 1)];
array[max - (loop + 1)] = array[max - loop];
array[max - loop] = temp;
temp = 0;
cont = 'y';
}
else if (array[max - loop] == array[max - (loop + 1)])
{
array[max - (loop + 1)] = 0;
cont = 'y';
}
}
//print "cont" value and pause
printf ("%c\n", cont);
scanf ("%d", &temp);
temp = 0;
} while (cont = 'y');
for (loop = 0; loop <= max; loop++)
{
if (array[loop] != 0)
{
fprintf (fp,"\t%d", array[loop]);
}
}
fclose (fp);
}