Getting very confused

Hey guys, i've got a problem and the more i think about it the more i get confused. I have a program that adds ramdomly generated values of details about hills, gives that information to a node and then adds the node to a linkedlist, it odes this 40 times. I then have to create a function to go through the linked list and sort the hills by height. To be honest, i dont even really know how to start the sorting function. Im really new to C++ and any help would be really appreciated!

this is the basic structure of my hills and nodes

HEADER

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
#include <iostream>
using namespace std;

struct hill
{	
	int height;									int distanceFromHome;							bool climbed;								
	int gridReference;							
};

struct Node
{											hill* data;									Node *link;								
};	

class LinkedList
{								
	private:
		Node *head;							
		Node *last;							
		int count;							
			
	public:
		LinkedList();							
		void addAnotherHill(hill *newInfo);     
		void displayDetails();					
		void sort(LinkedList &list);							
		void transferToArray();					

};


Cheers

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.
Topic archived. No new replies allowed.