Giudoku Official Site
Bubble sort

Bubble sort is the simplest method of sorting, with a complexity of O(n²).
It's got this particular name because the minimum elements slowly "float" at the beginning of the array, while the biggest ones "sink" at the bottom.
You can see this by printing the array after each iteration.

Just another note: if you are wondering what the hell that swap function is trying to do, reads the comments on the selection sort code. Isn't that nice?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define SIZE 10

void printArray(int []);
void bubbleSort(int []);
void swap(int[], int, int);
void fillRandomArray(int[]);

int main(int argc, char *argv[])
{
	int v[SIZE];
	fillRandomArray(v);
	
	printf("Current array is: ");
	printArray(v);
	bubbleSort(v);
	printf("After sorting: ");
	printArray(v);

	return 0;
}

void bubbleSort(int v[])
{
	int i, j;
	
	for (i = 0; i < SIZE; i++)
	{
		for (j = 0; j < SIZE-1; j++)
		{
			if (v[j] > v[j+1])
			{
				swap(v, j, j+1);
			}
		}
	}
}
				

void printArray(int v[])
{
	int i;
	
	for (i = 0; i < SIZE; i++)
	{
		printf("%d, ", v[i]);
	}
	printf("\n");
}

void swap(int v[], int index1, int index2)
{
	v[index1] ^= v[index2];
	v[index2] ^= v[index1];
	v[index1] ^= v[index2];
}

/*
 * Just to add a bit of randomness to everything
 */
void fillRandomArray(int v[])
{
	int i;
	
	srand(time(NULL));
	for (i = 0; i < SIZE; i++)
	{
		v[i] = rand() % SIZE;
	}
}