data structure – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sat, 15 Jul 2023 13:56:36 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg data structure – Programmerbay https://programmerbay.com 32 32 LinkedHashSet Class in Java With Program Example https://programmerbay.com/linkedhashset-class-in-java-with-program-example/ https://programmerbay.com/linkedhashset-class-in-java-with-program-example/#respond Sat, 15 Jul 2023 13:56:36 +0000 https://programmerbay.com/?p=9406 LinkedHashet is an implementation class of the Set interface which also extends the HashSet class. It was introduced in Java 1.4 version. It behaves in the same manner as HashSet except that it preserves or maintains the insertion order of elements inserted in the set. In simple words, It is an implementation of the set interface that stores and manipulates an ordered collection of elements.
It simply means the order in which elements are inserted, can be retrieved in the same order.

Screenshot from 2023 07 10 23 23 20

Points to Remember:

1) Hash Table and Linked List are its underlying data structure

2) It extends HashSet class and implements Set interface
3) It preserves insertion order
4) It permits only unique elements, similar to HashSet
5) It allows at most single null value
6) It offers a constant time performance for all the basic operations
7) It is less expensive than HashSet when comes to iterating over elements

Syntax:

Set<T> set = new LinkedHashSet<T>();

It is an implementation class that uses hash table and linked list data structure as its underlying data structure. It differs from HashSet with the exception that it maintains a doubly linked list to all the elements. It preserves insertion order with the help of a linked list which defines iteration order and makes sure the elements must be retrieved in the same order as they were previously inserted. It allows a single null element. It provides constant time performance for the basic operations.

There are 4 constructors provided in LinkedHashSet class:

1) LinkedHashSet()

A default constructor to create an empty linked hash set with default initial capacity and load factor.

LinkedHashSet<T> linkedHashSet = new LinkedHashSet<T>();

2) LinkedHashSet(collectionObj) 

It creates a new linked hash set having elements present in passed collection object.

ArrayList<T> list = new ArrayList<>();

LinkedHashSet<T> linkedHashSet = new LinkedHashSet<T>(list);

3) LinkedHashSet(int initialCapacity) :

It creates an empty linked hash set with specified capacity and default load factor.

LinkedHashSet<T> linkedHashSet = new LinkedHashSet<T>(4);

4) LinkedHashSet(int initialCapacity, float loadFactor):

It creates an empty linked hash set with mentioned capacity and load factor.

LinkedHashSet<T> linkedHashSet = new LinkedHashSet<T>(4,0.8);

Methods of LinkedHashSet Class

Method NameExplanation
add(Object)The method adds an element in a given set, returns false if one tries to add duplicate element
addAll(CollectionObj)It adds all the elements of the given collection in a given set
clear()It removes all elements from the given set
contains(Object)It checks whether the given object consists in a set or not, if it returns true if exist, otherwise false
containsAll(CollectionObj)It returns true, if all the elements of the given collection exist in the set, otherwise false
isEmpty()It checks whether a set is empty or not. it returns if empty, other false
iterator()It provides iterator object to iterate through set
remove(Object)It removes the given object from the set, if present
retainAll(CollectionObj)It retains elements of the collection provided in the method, and removed all other elements in the set that don't match the elements of collection object
size()It returns number of elements present in a set
spliterator()it returns spliterator object to iterate through set
toArray()It converts given set and returns array
removeAll(CollectionObj)It removes all the elements consisting in the collection object

Java Program to create LinkedHashSet instance and demonstrate its basic operations

Program:

import java.util.*;

public class SetExample {
    public static void main(String[] args) {

        Set<Integer> linkedHashSet = new LinkedHashSet<>(); // creating a linked hashset instance that holds integers

        // Adding elements to linked hash set
        linkedHashSet.add(5);
        linkedHashSet.add(1);
        linkedHashSet.add(null);  // adding nul value
        linkedHashSet.add(100);

        // Displaying Stored elements
        System.out.println(linkedHashSet);

        // removing null element from linked hash set

        linkedHashSet.remove(null);

        //Displaying after removing null

        System.out.println(linkedHashSet);

        // iterating through hash set

        Iterator iterator = linkedHashSet.iterator(); // getting iterator object
        System.out.println("Iterating over all the element of linked hash set :: ");
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }


    }
}

Output:

[5, 1, null, 100]
[5, 1, 100]
Iterating over all the element of linked hash set :: 
5
1
100

Basic Operations of LinkedHashSet

1) Adding element

HashLinkedSet supports add() and addAll() method to add elements in a given set

add(element) : It adds a given element to the set
addAll(collectionObj): It adds all the elements provided in collection object.

Java program to demonstrate add operation in LinkedHashSet

Program:

import java.util.*;

public class SetExample {
public static void main(String[] args) {

Set<Integer> linkedHashSet = new LinkedHashSet<>(); // creating a linked hashset instance that holds integers

// Adding elements to linked hash set
linkedHashSet.add(5);
linkedHashSet.add(1);

// Displaying Stored elements
System.out.println(linkedHashSet);

// add All method to add multiple elements

linkedHashSet.addAll(Arrays.asList(100,101,102,103));

//Displaying after addAll

System.out.println(linkedHashSet);


}
}

Output:

[5, 1]
[5, 1, 100, 101, 102, 103]

2) Removing element

There are two methods namely, remove() and removeAll() used for removing single or multiple elements from a set.
remove(element) : It removes the given element from the given set.
remove(collectionObj) : It removes all the elements present in the collection object from the given set.

Java program to demonstrate remove operation in LinkedHashSet

Program:

import java.util.*;

public class SetExample {
public static void main(String[] args) {

Set<Integer> linkedHashSet = new LinkedHashSet<>(); // creating a linked hashset instance that holds integers

// Adding elements to linked hash set
linkedHashSet.add(5);
linkedHashSet.add(1);

linkedHashSet.add(2);
linkedHashSet.add(100);
linkedHashSet.add(101);
linkedHashSet.add(102);
// Displaying Stored elements
System.out.println(linkedHashSet);

// removing single element the linked hash set

linkedHashSet.remove(2);

System.out.println("Removed 2 :: "+linkedHashSet);

// removeAll for remove multiple elements

linkedHashSet.removeAll(Arrays.asList(100,101,102));

//Displaying after removeAll

System.out.println("Removed 100, 101,102 from set :: "+linkedHashSet);


}
}

Output:

[5, 1, 2, 100, 101, 102]
Removed 2 :: [5, 1, 100, 101, 102]
Removed 100, 101,102 from set :: [5, 1]

3) Iterating over elements

There are multiple ways to iterate over a linked hash set. These are the following :-
1) iterator()
2) forEach()
3) Using Java 8 streams

Java program to demonstrate iteration operation over elements of a linked hash set object

Program:

import java.util.*;

public class SetExample {
public static void main(String[] args) {

Set<Integer> linkedHashSet = new LinkedHashSet<>(); // creating a linked hashset instance that holds integers

// Adding elements to linked hash set
linkedHashSet.add(5);
linkedHashSet.add(1);

linkedHashSet.add(2);
linkedHashSet.add(100);
linkedHashSet.add(101);

// Iterating using for each

System.out.println("Iterating using foreach :: ");
for (Integer element:
linkedHashSet) {
System.out.println(element);
}

// Iterating using iterator object
System.out.println("Iterating using iterator :: ");

Iterator iterator = linkedHashSet.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}

System.out.println("Iterating using stream :: ");

linkedHashSet.stream().forEach(e-> System.out.println(e));
}
}

 

Output:

Iterating using foreach ::
5
1
2
100
101
Iterating using iterator ::
5
1
2
100
101
Iterating using stream ::
5
1
2
100
101

 

]]>
https://programmerbay.com/linkedhashset-class-in-java-with-program-example/feed/ 0
Difference Between Linear Search And Binary Search in Tabular Form https://programmerbay.com/difference-between-linear-search-and-binary-search/ https://programmerbay.com/difference-between-linear-search-and-binary-search/#respond Wed, 12 Aug 2020 16:52:58 +0000 https://www.programmerbay.com/?p=2568 Searching algorithms are used to check whether an element exists in the given data structure or not. And likewise, if it is found then relevant operation would be performed on it.

Based on the traversing mechanism, it can be classified into two categories.  Linear Search and Binary Search. 

Binary search vs linear search

Linear Search iterates over elements sequentially to find data stored in the given list, whereas, Binary Search randomly compares the middle element of a list with desired data on each iteration and uses divide and conquer approach.

Difference between Binary Search and Linear Search in Tabular form

BasisLinear SearchBinary Search
AlgorithmIt sequentially searches an element by comparing each element stored in the given list from start to endIt is based on divide and conquer rule. It searches position of a target value within a sorted array
Sorted ListIt is not mandatory to have a sorted list It is mandatory to have a list to be sorted
WorkingThe algorithm works by checking each and every element sequentially at a time until a match is foundThe algorithm works by slicing a sorted list into two halves from the middle on each iteration until position of a target value is found
ImplementationIt can implemented on data structures which allow traversal atleast in one way such as arrays and Linked list It can be implemented on data structures that supports two way traversal only
Simplicity and ComplexitySimpler and less complex than Binary searchMore complex than Linear search
ApproachIt follows sequential approach and is iterative in nature It follows Divide and Conquer rule
Time ComplexityThe time complexity for Linear search is O(n) The time complexity for Binary search is O(log n)
EfficiencyIt is not efficient when it comes to search in large data set It is efficient as compared to Linear Search
Best CaseThe best case occurs when a matching element is found at first position of an arrayThe best case occurs when a matching element is found at first split which is the middle element of an array
Also KnownIt is also known as Sequential SearchIt is also known as half-interval search and logarithmic search

Linear Search or Sequential Search

Linear search, also refereed as Sequential search is a simple technique to search an element in a list or data structure.

It works by sequentially comparing desired element with other elements stored in the given list, until a match is found. In simple other words, it searches an element by iterating over items one by one from start to end. 

It is one of the simplest technique to search an element, but also costly and slower when it comes to work with a large datasets.

Further, it is considered to be practical when element list size is small or performing a single search on unsorted list. It is not efficient as Binary Search. 

Linear Search 1These are the following steps in the manner in which linear search works:

  1.  Get search element as input from the user
  2. Start Comparing the search element with first element of the given list
  3. If a match is found, print ‘element is found’ and terminate the method
  4. Otherwise, compare the search element with the next upcoming element of the list.
  5. Repeat third and fourth steps until a match is found .
  6. Compare last element of the list with search element, if still no match is found, print “element doesn’t exist” and terminate the method.

Important Points to Remember in Case of Linear Search

– An algorithm that sequentially searches an element in the given list, without skipping any item
– It follows sequential approach to find an element
– It applies on sequence containers ( that can be accessed sequentially ) such as array,deque, linked list and vector
– It is not mandatory to have an ordered element list, therefore, it is easy to use
– In linear search, performance is calculated using equality comparisons
– O(n) is the worst case scenario in linear search which happens when a searching element is the last element in the list
– O(1) is the best case scenario in linear search which happens when a searching element is matched at very first comparison in the list
– O(n) (n represents number of elements in input range) is the time complexity of linear search.

Binary Search 

It is a more efficient method than Linear search and one of the popular ones for searching an element stored in a data structure. 

It is mandatory to a list to be sorted.

Based on divide and conquer mechanism, it slices a list into two halves by dividing it from the middle on each iteration.

The middle item is then compared with the searching element if it is greater than the current one ( middle element)  then the further search would be performed on right sub-array, discarding left one. The same process would be followed again until a match is not found.

 

The first step is mandatory, List should be sorted,

search 1

Now, Slice it from the middle into two sub-array  ( In this case, Index 3 is at middle) and compare the element at that position with searching element which is 25

search 2

Since, 25 > 15

Therefore, we moved to the right as greater numbers are lying towards the right by Discarding Left ones

search 3

search 4

Important Points to Remember in Case of Binary Search

– An algorithm that searches an element by comparing middle or target value, calculated by dividing the given sorted list in two halves on each iteration
– It follows divide and conquer rule
– It applies on data structures where two-way traversal is applicable such as array
– It is not mandatory to have an ordered element list, therefore, it is a bit complex
– In linear search, performance is calculated using ordering comparisons
– O(Log n) is the worst case scenario in binary search
– O(1) is the best case scenario in binary search which happens when a searching element is matched at very first middle element in the list
– O(log n) (n represents number of elements in input range) is the time complexity of binary search

Important Differences

  1. A linear search checks single data at any given moment, without bouncing to any other thing. Conversely, binary search chops down your search to half when you locate the center of a sorted list.
  2. Time taken to search components continue to increase as the number of components is increased while searching through the linear process. Yet, binary search packs the searching time frame by separating the entire array into two halves.
  3. In a linear search, the elements are accessed sequentially, whereas; in binary search, the elements are accessed randomly.
  4. There is no need to sort data in a linear search while in binary search, the elements need to sort first.
  5. Linear search is considered to be effective for the small amount of data, whereas; binary search can efficiently handle large as well as small amounts of data.
  6. Example:

C++ Program to implement Linear Search

#include <iostream>

using namespace std;

int main ()
{

  int searchElement, arrList[5] = { 10, 43, 3, 21, 5 };
  int flag = 0;
  cout << "Enter value to search  : ";
  cin >> searchElement;
  for (int i = 0; i < 5; i++)
    if (arrList[i] == searchElement)
      {
  cout << "\n Element is Found";
  flag = 1;
  break;
      }

  if (flag == 0)
    cout << "Element does not exist!" ;
    return 0;
}

Output:

Enter value to search : 21
Element is Found

C++ program to implement Binary Search –

#include <iostream>

using namespace std;

int main() {

int f,l,mid,n,s,arr[10];
cout<<"enter no. of elements";
cin>>n;

for(int c=0;c<n;c++)
{
cin>>arr[c];
}
cout<<"enter value to search";
cin>>s;
f = 0;
l = n - 1;
mid = (f+l)/2;

while (f <= l) {
if (arr[mid] < s) {
f = mid + 1;
}
else if (arr[mid] == s) {
cout<<"element found";
break;
}
else{
l = mid - 1;
}
mid = (f + l)/2;

}

if (f > l)
{
cout<<"not found" ;
}
return 0;
}

Output:

enter no. of elements : 5
Provide the values : 23
4
54
3
23
enter value to search : 54
element found

]]>
https://programmerbay.com/difference-between-linear-search-and-binary-search/feed/ 0
What is Binary Search Tree and its Operations? https://programmerbay.com/what-is-binary-search-tree-and-its-operations/ https://programmerbay.com/what-is-binary-search-tree-and-its-operations/#respond Sat, 13 Jun 2020 17:07:02 +0000 https://www.programmerbay.com/?p=2928 What is Binary Search Tree ?

In Data structures, a binary search tree is a linked data structure that provides a way to store data orderly. All stored keys should satisfy the properties of a Binary search tree. These properties are:

  • Nodes of right subtree always have a value greater than the parent’s node
  • Nodes of left subtree always have value lesser than the parent’s node

It requires O(log n) time to perform basic operations in the average case. However, basic operations on BST take time proportional to the height of the tree.

Each node represents an object that consists link to the right subtree, a key value associated with the node, and a link to left subtree. If any parent or child node is missing, then it would be represented as NIL value.

image 2020 12 26 190922
Figure : Binary Search Tree Example

Binary search tree supports operations such as Insertion, Deletion, Searching of a node in the tree and also allow us to find Minimum, Maximum, Successor and Predecessor. Apart from that, a BST can be traversed in three-ways Inorder traversal, post-order traversal, and pre-order traversal.

Basic Operations in Binary Search Tree

  • Search Operation

A search operation starts from the root node to all the way downward recursively. The targeted element is compared with the root node, if both are equal then the search would get terminated.

If it is smaller than the root node then the search goes on at left subtree. And if the targeted value is greater, then search operation would be performed left subtree recursively.

  • Insertion and deletion

To insert a given element, BST first performs search operation, starting from the root node in order to locate the insertion position. Ones a NIL location is found then insertion is performed.

To delete a key from a BST we must know three cases:
1) If the targeted element has no child then remove the element and place NIL.
2) If the targeted element has only a single child, in this case, we just fill that place by simply putting its child node in its position.
3) If it has two children, then the key greater then the targeted value or Successor of targeted value would replace it.

  • Minimum and Maximum

A minimum key in a BST can be figured out by traversing left subtree from root node till a NIL is not encountered.

Similarly, A maximum key in a BST can be figured out by traversing right subtree from root node till a NIL is not encountered.

  • Successor and predecessor

A successor node for a given key value of BST can be derived without performing any comparison. If there is an immediate key available which is greater than the given node then the value would be returned otherwise NIL would be returned.

A predecessor node for a given key value of BST can be derived, if there is an immediate key smaller than given node then the value would be returned otherwise NIL.

  • Traversal 

Traversing refers to visit each and every node of a tree. Binary search tree can be traversed in three ways

In-order traversal

In this way of traversing a tree, we start from visiting all the nodes of left subtree, then root and then lastly right subtree

Pre-order traversal

In this way of traversing a tree, we start from the root, then visit all the nodes of left subtree and then last traverse right subtree

Post-order traversal

In this way of traversing a tree, we start from visiting all the nodes of left subtree, then all the nodes of the right subtree and then lastly root

]]>
https://programmerbay.com/what-is-binary-search-tree-and-its-operations/feed/ 0