Open In App

Self Organizing List : Count Method

Last Updated : 09 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Self Organizing list is a list that re-organizes or re-arranges itself for better performance. In a simple list, an item to be searched is looked for in a sequential manner which gives the time complexity of O(n). But in real scenario not all the items are searched frequently and most of the time only few items are searched multiple times. 

So, a self organizing list uses this property (also known as locality of reference) that brings the most frequent used items at the head of the list. This increases the probability of finding the item at the start of the list and those elements which are rarely used are pushed to the back of the list. 

In Count Method, the number of time each node is searched for is counted (i.e. the frequency of search is maintained). So an extra storage is associated with each node that is incremented every time a node is searched. And then the nodes are arranged in non-increasing order of count or frequency of its searches. So this ensures that the most frequently accessed node is kept at the head of the list. 

Examples:

Input : list : 1, 2, 3, 4, 5
searched : 4
Output : list : 4, 1, 2, 3, 5
Input : list : 4, 1, 2, 3, 5
searched : 5
searched : 5
searched : 2
Output : list : 5, 2, 4, 1, 3
Explanation : 5 is searched 2 times (i.e. the
most searched) 2 is searched 1 time and 4 is
also searched 1 time (but since 2 is searched
recently, it is kept ahead of 4) rest are not
searched, so they maintained order in which
they were inserted.

Implementation:

CPP




// CPP Program to implement self-organizing list
// using count method
#include <iostream>
using namespace std;
 
// structure for self organizing list
struct self_list {
    int value;
    int count;
    struct self_list* next;
};
 
// head and rear pointing to start and end of list resp.
self_list *head = NULL, *rear = NULL;
 
// function to insert an element
void insert_self_list(int number)
{
    // creating a node
    self_list* temp = (self_list*)malloc(sizeof(self_list));
 
    // assigning value to the created node;
    temp->value = number;
    temp->count = 0;
    temp->next = NULL;
 
    // first element of list
    if (head == NULL)
        head = rear = temp;
 
    // rest elements of list
    else {
        rear->next = temp;
        rear = temp;
    }
}
 
// function to search the key in list
// and re-arrange self-organizing list
bool search_self_list(int key)
{
    // pointer to current node
    self_list* current = head;
 
    // pointer to previous node
    self_list* prev = NULL;
 
    // searching for the key
    while (current != NULL) {
 
        // if key is found
        if (current->value == key) {
 
            // increment the count of node
            current->count = current->count + 1;
 
            // if it is not the first element
            if (current != head) {
                self_list* temp = head;
                self_list* temp_prev = NULL;
 
                // finding the place to arrange the searched node
                while (current->count < temp->count) {
                    temp_prev = temp;
                    temp = temp->next;
                }
 
                // if the place is other than its own place
                if (current != temp) {
                    prev->next = current->next;
                    current->next = temp;
 
                    // if it is to be placed at beginning
                    if (temp == head)
                        head = current;
                    else
                        temp_prev->next = current;
                }
            }
            return true;
        }
        prev = current;
        current = current->next;
    }
    return false;
}
 
// function to display the list
void display()
{
    if (head == NULL) {
        cout << "List is empty" << endl;
        return;
    }
 
    // temporary pointer pointing to head
    self_list* temp = head;
    cout << "List: ";
 
    // sequentially displaying nodes
    while (temp != NULL) {
        cout << temp->value << "(" << temp->count << ")";
        if (temp->next != NULL)
            cout << " --> ";
 
        // incrementing node pointer.
        temp = temp->next;
    }
    cout << endl
        << endl;
}
 
// Driver Code
int main()
{
    /* inserting five values */
    insert_self_list(1);
    insert_self_list(2);
    insert_self_list(3);
    insert_self_list(4);
    insert_self_list(5);
 
    // Display the list
    display();
 
    search_self_list(4);
    search_self_list(2);
    display();
 
    search_self_list(4);
    search_self_list(4);
    search_self_list(5);
    display();
 
    search_self_list(5);
    search_self_list(2);
    search_self_list(2);
    search_self_list(2);
    display();
    return 0;
}


Java




import java.util.*;
 
public class SelfList {
    static class Node {
        int value;
        int count;
        Node next;
 
        Node(int value) {
            this.value = value;
            this.count = 0;
            this.next = null;
        }
    }
 
    static Node head = null;
    static Node rear = null;
 
    // Method to insert a node with a given value to the end of the list
    static void insertSelfList(int number) {
        Node temp = new Node(number);
 
        if (head == null)
              // If list is empty, the new node becomes both the head and rear
            head = rear = temp;
        else {
              // Else the new node is added to the rear
            rear.next = temp;
              // Rear is updated to the new node
            rear = temp;
        }
    }
 
    // Method to search for a node with a given key in the list
    static boolean searchSelfList(int key) {
        Node current = head;
        Node prev = null;
 
        while (current != null) {
            if (current.value == key) {
                current.count++;
 
                if (current != head) {
                    Node temp = head;
                    Node tempPrev = null;
 
                    // Finding the position to rearrange the searched node based on its count
                    while (current.count < temp.count) {
                        tempPrev = temp;
                        temp = temp.next;
                    }
 
                    if (current != temp) {
                          // Removing the current node from its current position
                        prev.next = current.next;
                          // Rearranging the node
                        current.next = temp;
                        if (temp == head)
                              // If the rearranged position is the head, update the head
                            head = current;
                        else
                              // Else, rearrange the previous node's pointer
                            tempPrev.next = current;
                    }
                }
                return true;
            }
            prev = current;
            current = current.next;
        }
        return false; // Node not found
    }
 
    // Display the list
    static void display() {
        if (head == null) {
            System.out.println("List is empty");
            return;
        }
 
        Node temp = head;
        System.out.print("List: ");
 
        // Display the nodes in the list
        while (temp != null) {
            System.out.print(temp.value + "(" + temp.count + ")");
            if (temp.next != null)
                System.out.print(" --> ");
            temp = temp.next;
        }
        System.out.println("\n");
    }
 
    // Main method
    public static void main(String[] args) {
        // Insert initial nodes
        insertSelfList(1);
        insertSelfList(2);
        insertSelfList(3);
        insertSelfList(4);
        insertSelfList(5);
 
        display(); // Display initial list
 
        searchSelfList(4);
        searchSelfList(2);
        display(); // Display list after search operations
 
        searchSelfList(4);
        searchSelfList(4);
        searchSelfList(5);
        display(); // Display list after more search operations
 
        searchSelfList(5);
        searchSelfList(2);
        searchSelfList(2);
        searchSelfList(2);
        display(); // Display list after additional search operations
    }
}


Python3




# Python3 Program to implement self-organizing list
# using count method
 
# self organize list class
class self_organize_list(object):
  # default constructor
  def __init__(self):
    self.__list = list()
    self.__size = 0
   
  # constructor to initialize list
  def __init__(self, lst):
    self.__list = [ [x, 0] for x in lst ]
    self.__size = len(lst)
 
  # method to display the list
  def display(self):
    print(self.__list)
 
  # method to search key in list
  def search(self, key):
    index = -1
    # find key in search organize list
    for i in range(self.__size):
      if self.__list[i][0] == key:
        index = i
        break
         
    # check if key found
    if index == -1:
      return False
    # Increment the frequency of key
    self.__list[index][1] = self.__list[index][1] + 1
    # finding new position for the key
    new_pos = index
    for i in range(index-1, -1, -1):
      if self.__list[index][1] >= self.__list[i][1]:
        new_pos = i
    # Inserting the key in new position
    bkp = self.__list[index]
    self.__list.pop(index)
    self.__list.insert(new_pos, bkp)
    return True
     
  # method to insert key in self organize list
  def insert(self, key):
    self.__list.append([key, 0])
    self.__size = self.__size + 1
 
if __name__ == "__main__":
  # initial list of four elements
  lst = [1, 2, 3, 4]
  sol = self_organize_list(lst)
   
  # inserting new element and display
  sol.insert(5)
  sol.display()
 
  # sequence of search and display
  sol.search(4)
  sol.search(2)
  sol.display()
 
  # sequence of search and display
  sol.search(4)
  sol.search(4)
  sol.search(5)
  sol.display()
 
  # sequence of search and display
  sol.search(5)
  sol.search(2)
  sol.search(2)
  sol.search(2)
  sol.display()


C#




using System;
 
// Structure for self-organizing list
public class SelfList
{
    public int Value { get; set; }
    public int Count { get; set; }
    public SelfList Next { get; set; }
}
 
class Program
{
    // Head and rear pointing to start and end of the list, respectively.
    static SelfList head = null, rear = null;
 
    // Function to insert an element into the self-organizing list
    static void InsertSelfList(int number)
    {
        // Creating a node
        SelfList temp = new SelfList
        {
            Value = number,
            Count = 0,
            Next = null
        };
 
        // First element of the list
        if (head == null)
        {
            head = rear = temp;
        }
        // Rest elements of the list
        else
        {
            rear.Next = temp;
            rear = temp;
        }
    }
 
    // Function to search the key in the list and rearrange the self-organizing list
    static bool SearchSelfList(int key)
    {
        // Pointer to the current node
        SelfList current = head;
 
        // Pointer to the previous node
        SelfList prev = null;
 
        // Searching for the key
        while (current != null)
        {
            // If key is found
            if (current.Value == key)
            {
                // Increment the count of the node
                current.Count++;
 
                // If it is not the first element
                if (current != head)
                {
                    SelfList temp = head;
                    SelfList tempPrev = null;
 
                    // Finding the place to arrange the searched node
                    while (current.Count < temp.Count)
                    {
                        tempPrev = temp;
                        temp = temp.Next;
                    }
 
                    // If the place is other than its own place
                    if (current != temp)
                    {
                        prev.Next = current.Next;
                        current.Next = temp;
 
                        // If it is to be placed at the beginning
                        if (temp == head)
                            head = current;
                        else
                            tempPrev.Next = current;
                    }
                }
                return true;
            }
            prev = current;
            current = current.Next;
        }
        return false;
    }
 
    // Function to display the list
    static void Display()
    {
        if (head == null)
        {
            Console.WriteLine("List is empty");
            return;
        }
 
        // Temporary pointer pointing to head
        SelfList temp = head;
        Console.Write("List: ");
 
        // Sequentially displaying nodes
        while (temp != null)
        {
            Console.Write($"{temp.Value}({temp.Count})");
            if (temp.Next != null)
                Console.Write(" --> ");
 
            // Incrementing node pointer.
            temp = temp.Next;
        }
        Console.WriteLine("\n");
    }
 
    // Driver Code
    static void Main()
    {
        /* Inserting five values */
        InsertSelfList(1);
        InsertSelfList(2);
        InsertSelfList(3);
        InsertSelfList(4);
        InsertSelfList(5);
 
        // Display the list
        Display();
 
        SearchSelfList(4);
        SearchSelfList(2);
        Display();
 
        SearchSelfList(4);
        SearchSelfList(4);
        SearchSelfList(5);
        Display();
 
        SearchSelfList(5);
        SearchSelfList(2);
        SearchSelfList(2);
        SearchSelfList(2);
        Display();
    }
}


Javascript




// JavaScript Program to implement a self-organizing list
// using count method
 
// Structure for self-organizing list
class SelfList {
    constructor(value) {
        this.value = value;
        this.count = 0;
        this.next = null;
    }
}
 
// Head and rear pointing to start and end of list respectively
let head = null;
let rear = null;
 
// Function to insert an element
function insertSelfList(number) {
    // Creating a node
    const temp = new SelfList(number);
 
    // First element of list
    if (head === null)
        head = rear = temp;
    // Rest elements of list
    else {
        rear.next = temp;
        rear = temp;
    }
}
 
// Function to search the key in the list
// and rearrange the self-organizing list
function searchSelfList(key) {
    // Pointer to current node
    let current = head;
 
    // Pointer to previous node
    let prev = null;
 
    // Searching for the key
    while (current !== null) {
        // If key is found
        if (current.value === key) {
            // Increment the count of node
            current.count++;
 
            // If it is not the first element
            if (current !== head) {
                let temp = head;
                let tempPrev = null;
 
                // Finding the place to arrange the searched node
                while (current.count < temp.count) {
                    tempPrev = temp;
                    temp = temp.next;
                }
 
                // If the place is other than its own place
                if (current !== temp) {
                    prev.next = current.next;
                    current.next = temp;
 
                    // If it is to be placed at the beginning
                    if (temp === head)
                        head = current;
                    else
                        tempPrev.next = current;
                }
            }
            return true;
        }
        prev = current;
        current = current.next;
    }
    return false;
}
 
// Function to display the list
function display() {
    if (head === null) {
        console.log("List is empty");
        return;
    }
 
    // Temporary pointer pointing to head
    let temp = head;
    let result = "List: ";
 
    // Sequentially displaying nodes
    while (temp !== null) {
        result += `${temp.value}(${temp.count})`;
        if (temp.next !== null)
            result += " --> ";
 
        // Incrementing node pointer.
        temp = temp.next;
    }
    console.log(result + "\n");
}
 
// Driver Code
(function main() {
    // Inserting five values
    insertSelfList(1);
    insertSelfList(2);
    insertSelfList(3);
    insertSelfList(4);
    insertSelfList(5);
 
    // Display the list
    display();
 
    searchSelfList(4);
    searchSelfList(2);
    display();
 
    searchSelfList(4);
    searchSelfList(4);
    searchSelfList(5);
    display();
 
    searchSelfList(5);
    searchSelfList(2);
    searchSelfList(2);
    searchSelfList(2);
    display();
})();


Output

List: 1(0) --> 2(0) --> 3(0) --> 4(0) --> 5(0)

List: 2(1) --> 4(1) --> 1(0) --> 3(0) --> 5(0)

List: 4(3) --> 5(1) --> 2(1) --> 1(0) --> 3(0)

List: 2(4) --> 4(3) --> 5(2) --> 1(0) --> 3(0)





Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads