Since you are dealing with a relativly small number of data items (40), you can use a very basic sorting routing such as a bubble sort.
The algoithm is to go throught the list in order and compare adjacent elements, swapping if required to correct their order.
You then repeat as required until you have looed through without making a swap, at which point the list is sorted.
Each time you loop through the list you can reduce the effective end point by 1, so if the list is 40 long, you check 1 to 39 on loop 2, 1 to 38 on loop 3, etc, as each itteration through the loop moves the largest element to the end.
For an array of integers the routing woudl look something like
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
const int MAX = 100;
long numbers[MAX];
...
bool sorted = false;
long temp;
int end = MAX;
while (!sorted)
{
sorted = true;
end--;
for (int i=0; i < end; i++)
{
if (number[i] > number[i+1])
{
sorted = false;
temp = number[i];
number[i] = number[i+1];
number[i+1] = temp;
}
}
}
|
Of course with a linked list you cannot simply swap the elements, but instead need to swap the link pointers to reorder the two items.