I'm practicing my C skills by trying to code a program for rearranging array elements in ascending order by using a created function called Bubbleswap. TO fill up the array I've used the random number generator.
When I use the following code, I will get the message that Bubblesort function is missing a return value, while it shouldn't need one. And I think therefore the request to use bubbleswap function is not working properly.
//Opgave bubblesort functie
#include "toolbox.h"
#include <ansi_c.h>
#include <stdio.h>
#include <time.h>
// functies //
double bubblesort (double arrayA[], int n)
{
int a,b,swap;
for (a =0;a<(n - 1);a++)
{
for (b=0;b<(n - a - 1);b++)
{
if(arrayA[b]>arrayA[b+1]) // for decreasing order use <
{
swap = arrayA[b];
arrayA[b]= arrayA[b+1];
arrayA[b+1]=swap;
}
}
}
}
// main script //
int main()
{
int aantal,i; //variables
double arrayA[1000],arrayB[1000] ;
float r;
srand(time(NULL)); // to start the random seeds
printf(" Typ het aantal getallen in. \n"); //request the elements
scanf("%d", &aantal);
for(i=0; i<aantal;i++) // fill the array with random numbers
{
arrayA[i]=rand();
}
printf("Getallen in volgorde \n"); //re-arrange the numbers with the help of bubblesort
for (i=0; i<aantal;i++)
{
r = bubblesort(arrayA, aantal); //request the function bubblesort //r =arrayA[i];
printf("%.0f \n", r);
}
getchar();
getchar();
}
If I understood correctly due to your the comment //r =arrayA[i];
, to accomplish that you could change:
r = bubblesort(arrayA, aantal,i);
and:
double bubblesort (double arrayA[], int n,int i)
{
int a,b,swap;
for (a =0;a<(n - 1);a++)
{
for (b=0;b<(n - a - 1);b++)
{
if(arrayA[b]>arrayA[b+1]) // for decreasing order use <
{
swap = arrayA[b];
arrayA[b]= arrayA[b+1];
arrayA[b+1]=swap;
}
}
}
return arrayA[i];
}