Hi all,
I'm learning C for the first time as part of my engineering degree and one of my labs recently required that I write a Bubblesort algorithm (to demonstrate my use of pointers e.t.c.). But I couldn't do it!
We were given this snippet of code to start us off and a link to the Bubblesort wiki page to view the description and Pseudocode.
Code:
void sort(const int * input, int * output, const int size)
Now, I got so far as to do ONE successful pass.
E.g. from an array of numbers 9876543210 my program would give 8765432109.
Code:
#include <stdio.h>
#define ARRAY_SIZE 10
void sort(const int * input, int * output, const int size);
int main(void)
{
int mixed[ARRAY_SIZE] = { 9,8,7,6,5,4,3,2,1,0 };
int fixed[ARRAY_SIZE] = { 9,8,7,6,5,4,3,2,1,0 };
sort(mixed,fixed,ARRAY_SIZE);
}
void sort(const int * input, int * output, const int size)
{
int i = 0;
int temp;
for (i=0;i<size;++i)
{
if (output[i]>output[i+1])
{
temp = output[i];
output[i] = output[i+1];
output[i+1] = temp;
}
}
for (i=0;i<size;i+=1)
{
printf("%i\n",output[i]);
}
}
This code kinda sucks, I know. I didn't use pointers fully and "input" is not used at all. But I really don't know how to progress from here.
All the example code I've seen on the internet have a nested for loop, something like this:
Code:
- int i,j,t;
- for(i=n-2;i>=0;i--)
- {
- for(j=0;j<=i;j++)
- {
... So I was about to ask wtf is happening here - but I think I just figured it out. For every pass (limited by i, so that j+1 never exceeds the size of the array), i is decreased by 1 and the loop starts again!
Am I right?
Anyway... first post, hello all, I will probably be returning soon.
Still need to use pointers, though...