I am trying to implement the bubble sort algorithm in C. Here is what I have so far:
#include<stdio.h>
void bubble_sort(int m, int a[100000]);
void main()
{
int a[100000], i, m;
FILE * be;
be=fopen("be.txt","r");
for (i=0; !(feof(be)); ++i)
fscanf(be,"%i", a+i);
m=i-1;
bubble_sort(m ,a);
fclose(be);
}
void bubble_sort(int m, int a[100000])
{
int i, ok, v, n=m;;
for (;!ok;ok=1)
{
ok=0;
for (i=0;i<=m-1;++i)
{
if (*(a+i)>*(a+i+1)) { v=*(a+i); *(a+i)=*(a+i+1); *(a+i+1)=v; ok=0;}
}
m=m-1;
}
for (i=0; i<n; ++i)
printf("%i ", a[i]);
}
My pseudo code:
Bubblesort2( A )
m:=length( A ) - 1
repeat
OK := true
for i := 0 to m-1 do
if Ai > Ai+1 then
Ai <=>Ai+1
OK := false
m := m - 1
until OK
This doesn't work right. What is the code to implement he bubble sort in C?
Try this:
void bubble_sort(int m, int a[100000])
{
int i, ok = 0, v, n = m;
while ( !ok )
{
ok = 1;
for ( i=0; i < m-1; ++i )
{
if ( *(a+i) > *(a+i+1) )
{
v = *(a+i);
*(a+i) = *(a+i+1);
*(a+i+1) = v;
ok = 0;
}
}
m--;
}
for ( i = 0; i < n; ++i )
printf("%i ", a[i]);
}
Basically, initialize ok (local variables are initialized with garbage values). You also must set ok = 1 when entering the loop and ok = 0 if a swap took place. There's no point in using a for loop, a while loop is more readable. m = m - 1
can be replaced with m--
, it's the same thing and you write less code.