Suppose I have the following dataset stored in a linkedlist (excluding the header):
ID | Name
1 | John
2 | Albert
3 | Simon
Now, I would like to sort the nodes according to, say, alphabetical order.
I would like to know how I can come up with my own sorting method without using Arrays (and similar stuff like Lists, Vectors, ArrayLists etc.) and without using a library sorting method (e.g. Collections.sort).
In other words, I would like to know the concept of sorting and how one should go about arranging the nodes in a systematic manner. It doesn't have to be efficient - it just has to work.
I'll be trying this out in Java but I would appreciate pseudocodes or tips / hints / other resources as well.
Thank you.
Addendum:
LinkedList.java
class LinkedList
{
private Node head; // first node in the linked list
private int count;
public int getCount()
{
return count;
}
public Node getHead()
{
return head;
}
public LinkedList()
{
head = null; // creates an empty linked list
count = 0;
}
public void deleteFromFront()
{
if (count > 0)
{
Node temp = head;
head = temp.getLink();
temp = null;
count--;
}
}
public void AddToFront(Object cd)
{
Node newNode = new Node(cd);
newNode.setLink(head);
head = newNode;
count++;
}
public void RemoveAtPosition(int n)
{
int counter=1;
Node previous=null;
if(n==1)
deleteFromFront();
else if(n<=getCount())
for(Node j=head;j!=null;j=j.getLink())
{
if(counter==n&&previous!=null)
{
previous.setLink(j.getLink());
j.setLink(null);
}
previous=j;
counter++;
}
else
System.out.println("Unable to remove object at position "+n);
}
public void AddAtPosition(int n, Object cd)
{
int counter=1;
Node newNode=new Node(cd);
Node previous=null;
for(Node j=head;j!=null;j=j.getLink())
{
if(counter==n&&previous!=null)
{
newNode.setLink(j.getLink());
j.setLink(newNode);
}
previous=j;
counter++;
}
}
public void Swap(int n1, int n2)
{
// how do I swap nodes?
}
public void Sort()
{
// how do I sort nodes?
}
}
Node.java
public class Node {
private Object data;
private Node link;
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getLink() {
return link;
}
public void setLink(Node link) {
this.link = link;
}
public Node(Object data) {
this.data = data;
this.link = null;
}
}