Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Present an algorithm (in outline form) for inserting an element into a sorted li

ID: 3906527 • Letter: P

Question

Present an algorithm (in outline form) for inserting an element into a sorted linked list so that the list is always in sorted order. Do not utilize a sorting routine, but rather devise an insert (add) algorithm that will search the list and insert the new element in the proper place in the list so that the list is always in order. Assume that the objects involved all properly override both the equals (==) and the compareTo (>, <, >=, and <=) methods. The list is to be maintained in ascending order. Assume that the add method has the following signature. public void Add(E element) C#

Explanation / Answer

Given below is the code assuming you have a inner Node class like

class Node
{
E data;
Node next;

public Node(E val)
{
data = val;
next = null;
}
}


================
public void Add(E element)
{
//create a new node and set data and link part
Node n = new Node(element);

if(head == null) //is list empty?
head = n;
else
{
Node curr = head;
Node prev = null;

//find a node before which the new node should be inserted
while(curr != null)
{
if(element.compareTo(curr.data) < 0) //if new data is smaller than current node in list, we have found the place to insert
break;
  
prev = curr;
curr = curr.next;
}

n.next = curr; //set the new node's next to the node before which we will insert
if(curr == head) //insert before head node?
head = n;
else
prev.next = n; //link the previous node to the new node
}
  
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote