Posts

Showing posts from May, 2020

Binary Search in C#

          Binary Search in C# When you want to search for an element in an array, Binary Search comes into major play.  Most common logic for Binary Search is : 1) Sort the elements in an array 2) Using Loop or Recursion, split the array in half  3) Check for the element in the split array(either left or right).  PseudoCode:  Left =0 - Set Left index to begining of the array.  Right= Length of the array.  loop through the elements until left <= right  calculate mid - mid = left+right/2; if element we are searching is mid element, we  found the element and we exit.  if element we are searching is less than the mid element, we set the right Index to mid-1  if element we are searching is greater than the mid element, we set the start index to mid+1 public static int binary_search(int[] arr, int item) { int low = 0; int high = arr.Length; while (low...

SortedDictionary in C#

Sorted Dictionary in C# SortedDictionary in C# is useful in C# if you want to sort the elements based on the key.  Some important points to consider: Keys are always sorted.  SortedDictionary is a binary search tree with O(log n) retrieval time. It is used when you need faster insertion and removal.  Keys are always sorted in Ascending order. Some of the functionalities are common among Dictionary and Sorted Dictionary: Add() - To add key-value pair.  Example: Add(100, "Test"); Clear() - Removes all the keys from the SortedDictionary. Remove(TKey) - To remove the specified key from the SortedDictionary. ContainsKey(TKey) - To check if there is an element in the SortedDictionary with the specified value. ContainsValue(TValue)- To check if there is an element in the dictionary with the specified value. Disadvantages :  SortedDictionary has a slower retrieval time ( O(log n)) compared to Dictionary which has O(1)- Constan...