Data Structures Tutorial

Data Structures Tutorial Asymptotic Notation Structure and Union Array Data Structure Linked list Data Structure Type of Linked list Advantages and Disadvantages of linked list Queue Data Structure Implementation of Queue Stack Data Structure Implementation of Stack Sorting Insertion sort Quick sort Selection sort Heap sort Merge sort Bucket sort Count sort Radix sort Shell sort Tree Traversal of the binary tree Binary search tree Graph Spanning tree Linear Search Binary Search Hashing Collision Resolution Techniques

Misc Topic:

Priority Queue in Data Structure Deque in Data Structure Difference Between Linear And Non Linear Data Structures Queue Operations In Data Structure About Data Structures Data Structures Algorithms Types of Data Structures Big O Notations Introduction to Arrays Introduction to 1D-Arrays Operations on 1D-Arrays Introduction to 2D-Arrays Operations on 2D-Arrays Strings in Data Structures String Operations Application of 2D array Bubble Sort Insertion Sort Sorting Algorithms What is DFS Algorithm What Is Graph Data Structure What is the difference between Tree and Graph What is the difference between DFS and BFS Bucket Sort Dijkstra’s vs Bellman-Ford Algorithm Linear Queue Data Structure in C Stack Using Array Stack Using Linked List Recursion in Fibonacci Stack vs Array What is Skewed Binary Tree Primitive Data Structure in C Dynamic memory allocation of structure in C Application of Stack in Data Structures Binary Tree in Data Structures Heap Data Structure Recursion - Factorial and Fibonacci What is B tree what is B+ tree Huffman tree in Data Structures Insertion Sort vs Bubble Sort Adding one to the number represented an array of digits Bitwise Operators and their Important Tricks Blowfish algorithm Bubble Sort vs Selection Sort Hashing and its Applications Heap Sort vs Merge Sort Insertion Sort vs Selection Sort Merge Conflicts and ways to handle them Difference between Stack and Queue AVL tree in data structure c++ Bubble sort algorithm using Javascript Buffer overflow attack with examples Find out the area between two concentric circles Lowest common ancestor in a binary search tree Number of visible boxes putting one inside another Program to calculate the area of the circumcircle of an equilateral triangle Red-black Tree in Data Structures Strictly binary tree in Data Structures 2-3 Trees and Basic Operations on them Asynchronous advantage actor-critic (A3C) Algorithm Bubble Sort vs Heap Sort Digital Search Tree in Data Structures Minimum Spanning Tree Permutation Sort or Bogo Sort Quick Sort vs Merge Sort Boruvkas algorithm Bubble Sort vs Quick Sort Common Operations on various Data Structures Detect and Remove Loop in a Linked List How to Start Learning DSA Print kth least significant bit number Why is Binary Heap Preferred over BST for Priority Queue Bin Packing Problem Binary Tree Inorder Traversal Burning binary tree Equal Sum What is a Threaded Binary Tree? What is a full Binary Tree? Bubble Sort vs Merge Sort B+ Tree Program in Q language Deletion Operation from A B Tree Deletion Operation of the binary search tree in C++ language Does Overloading Work with Inheritance Balanced Binary Tree Binary tree deletion Binary tree insertion Cocktail Sort Comb Sort FIFO approach Operations of B Tree in C++ Language Recaman’s Sequence Tim Sort Understanding Data Processing

Bitwise Operators and their Important Tricks

In most of the programs you write today, you deal with data types comprising bytes, such as integer, float, double, etc. Dealing with bytes? It is a quite normal task, but to write efficient code and improve your logic, you need to go beyond this.

To perform operations like data encryption or data compression, you need to deal with a deeper level of storage structures. Since Bitwise operators work on the ground level in our system they are faster, they optimize the program to a good level.

Midnight hospitals are faster than normal operators as they deal directly with bit-level data and hence can be used to optimize the time complexity of different programs. Before going to the tricks, let's first brush up on some important concepts of Bitwise operations.

Following are the six widely used Bitwise operators:

  1. Not ~
  2. AND &
  3. OR |
  4. LEFT SHIFT <<
  5. RIGHT SHIFT >>
  6. XOR ^

Bitwise NOT

This is a unary operator used when you need to flip all the bits for a number. In other words, this operator returns the one's complement of a binary number.

For example,

X=2 =(010)2

~x=(101)2 =5

Bitwise AND

This is a binary operator, and as the name depicts, it just returns the output of the AND operation on each and every single bit of the two operands.

If both the bits that are being compared are 1, then only the result is one else; it is zero.

For example,

X=2 =(010)2

Y=5 =(101)2

X AND Y=(000)2 =0

Bitwise OR

This Binary operator just returns the output of or operation performed on each of the bits from on the two inputs.

For example,

X=2 =(010)2

Y=5 =(101)2

X OR Y=(111)2 =7

Bitwise XOR

This Bitwise operator takes two inputs of the same length and compares each of their bits. If both of the bits that are being compared are the same, then the result would be zero; else, it would return 1

For example,

X=2 =(010)2

Y=5 =(101)2

X XOR Y=(111)2 =7

Bitwise LEFT-SHIFT

This binary operator, technically speaking, shifts the n bits from the m number to the left and appends 0 at the end. Basically, it returns the value of m * 2^n, and if the two operands are m and n

For example,

X=1 =(01)2

Y=2 =(10)2

X << Y=(0100)2 =4

Or you can understand this as:

X= 1

Y= 2

X<< Y = 1*22 =4

Bitwise RIGHT-SHIFT

This binary operator, technically speaking this operator shifts the n bits from the m number to the right and appends 1 at the end. It basically returns the value of m / 2^n, where m and n are the two operands.

For example,

X=4 =(0100)2

Y=1

X << Y=(010)2 =2

Or you can understand this as:

X= 4

Y= 1

X>> Y = 4/21 =2

Tricks of Bit-Wise Operators

Now let’s move towards up of the important techniques or tricks that you can use in your programs welding with BITS in your straight should help you to write time-efficient quotes for the operations that you almost use in every algorithm in order to build a good program.

1. Swapping two numbers using Bitwise operators

 Algorithm to swap two numbers without using any kind of extra space as well as pointers:

  • Read inputs x and y.
  • Set x = x ^ y (X XOR Y).
  • Set y = y ^ x
  • Assign x ^ y to x again.
  • Print the swapped results

This is an efficient way to swap two variables in your program.

2. Calculate the XOR of all the numbers from 1 to n

By observing the XOR of all the numbers from 0 to n you would find a common pattern sequence in them.

Using the logic behind this pattern, an efficient algorithm can be designed in such a way that you would be able to find the XOR of all the numbers from 0 to n in constant time complexity.

The algorithm is:

  • Read N.
  • Calculate N%4.
  • Set I =N%4.
  • Check the value of I:

a) For I==0

Print N.

b) For I==1

Print N.

c) For I==2

Print N+1.

d) For I==3

Print 0.

This efficient way prints the XOR of 1 to n numbers in O(1) time complexity, whereas a normal algorithm with a naive approach would take O(N) time for the same.

Using bit operators, find a number's MSB (Most Significant Bit) efficiently

The most efficient way to find the most significant bit of a fixed-size interior would be to use an algorithm that should directly deal with the bits.

The algorithm to find the MSB would be:

  1. Read N.
  2. Set n= n | n >>1
  3. Set n= n | n >>2
  4. Set n= n | n >>4
  5. Set n= n | n >>8
  6. Set n= n | n >>16
  7. Set n = (( n+1)>>1 | (n & (1 <<((sizeof(n)*CHAR_BIT-1)));
  8. Return N.

This algorithm can find the most significant bit of a number in just O(1) time complexity.

Check if a number is a power of two.

You can directly use this trick to find whether a number is a power of two or not.

  1. Read n.
  2. Initialize result= n && (!(n&(n-1)))
  3. Return result.

Directly return TRUE OR FALSE in constant time and can help you to save a lot of time in many programs.

Convert a given binary number to an integer

The auto keyword in c is used for this task and returns the desired value

For example,

int main(){
auto value= 0b0110010
printf("%d", value);
}

Flipping all bits of a number

When you need to flip all the bits of a number, you can easily do the same by subtracting it from any number in which all the bits are set.

For example,

Number= 0011010

The number in which all the bits are set = 111111

Subtraction= 1100101 (numbers with flipped bits)

Algorithm:

  1. Read Number.
  2. Initialize n= number.
  3. Set n= n | n >>1
  4. Set n= n | n >>2
  5. Set n= n | n >>4
  6. Set n= n | n >>8
  7. Set n= n | n >>16
  8. Return (n - number).

Like this, you could get the number with all the flipped bits in constant time.

Check if the sequence of bits of any number has an alternate pattern.

Whenever you need to find any pattern in a sequence of bits, you can use the Bitwise XOR operation to check whether there is an alternate pattern.

The below algorithm can be used for the same.

  1. Read N
  2. Check the value of :((n+1)&n)
    • if it is equal to 0
      return 1.
    • else
      return 0.

This algorithm is a helpful trick you can use whenever you need to find any number with a specific type of bits sequence.

Finding the number of leading and trailing zeros in any number

You can directly use the inbuilt GCC function to find the number of leading and trailing zeros of any number.

For example:

  1. Read N
  2. Set leading_zero = ___builtin_clz(n).
  3. return leading_zero.

These are some useful Bitwise manipulation tricks you can use in your various programs to reduce their time complexity and hence write efficient codes.



ADVERTISEMENT
ADVERTISEMENT