Monday, March 28, 2011

Kata 2: Sorting a list of integers

C (http://ideone.com/Zf6rB)


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
#include <stdio.h>
#include <stdlib.h>

/*
Order an Array of integers, coding kata.
In C we will have to program our own sorting
algorithm. For simplicity our own very inefficient
sorting algorithm is used
*/

void printArray(int* list, int size);
void sortAscending(int* list, int size);


int main()
{
int size = 50;
int list[size];
// Initialize the array in reverse order
int i = 0;
for(i = size ; i > 0 ; i--)
{
list[size-i] = i;
}
printArray(list,size);
sortAscending(list,size);
printArray(list,size);

}

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

void sortAscending(int* list, int size){
// Variable to swap values
int aux;
// Variable to knwo when we are done ordering
int comparisonCounter = 0;
int index = 0;
while(index < size -1)
{
comparisonCounter++;
if( list[index] > list[index+1] )
{
aux = list[index];
list[index] = list[index+1];
list[index+1] = aux;
index = (--index >= 0)?index:0;
}
else
{
index++;
}
}
printf("Comparisons done = %d\n",comparisonCounter);
}