<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Data Structures and Algorithms - Crio Blog]]></title><description><![CDATA[Find unique project ideas, activity-based learning content, and career guidance to become a skilled software developer in product based companies.]]></description><link>https://www.crio.do/blog/</link><image><url>https://www.crio.do/blog/favicon.png</url><title>Data Structures and Algorithms - Crio Blog</title><link>https://www.crio.do/blog/</link></image><generator>Ghost 4.22</generator><lastBuildDate>Thu, 28 May 2026 18:38:38 GMT</lastBuildDate><atom:link href="https://www.crio.do/blog/tag/data-structures-and-algorithms/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Everything You Need To Know About Merge Sort]]></title><description><![CDATA[Learn the fundamentals of Merge Sort with an example. Sharpen your understanding with fun quizzes and activities.]]></description><link>https://www.crio.do/blog/merge-sort-algorithm-dsa/</link><guid isPermaLink="false">66c783bc134c11095afa9303</guid><category><![CDATA[Data Structures and Algorithms]]></category><category><![CDATA[Crio Community]]></category><dc:creator><![CDATA[Abheetha Pradhan]]></dc:creator><pubDate>Mon, 09 Sep 2024 11:29:00 GMT</pubDate><media:content url="https://www.crio.do/blog/content/images/2021/09/Merge-sort.png" medium="image"/><content:encoded><![CDATA[<img src="https://www.crio.do/blog/content/images/2021/09/Merge-sort.png" alt="Everything You Need To Know About Merge Sort"><p>Merge Sort is the perfect example of the <strong>Divide and Conquer</strong> algorithm design. Given an array, it divides the array into two halves, sorts these two halves recursively, and then, it merges the two smaller sorted arrays into a larger sorted array.<br>Amongst popular <strong>sorting algorithms</strong>, Merge Sort stands out for a reason. Do you know why?</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/09/Merge-sort-table.png" class="kg-image" alt="Everything You Need To Know About Merge Sort" loading="lazy" width="1776" height="881" srcset="https://www.crio.do/blog/content/images/size/w600/2021/09/Merge-sort-table.png 600w, https://www.crio.do/blog/content/images/size/w1000/2021/09/Merge-sort-table.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2021/09/Merge-sort-table.png 1600w, https://www.crio.do/blog/content/images/2021/09/Merge-sort-table.png 1776w" sizes="(min-width: 720px) 720px"></figure><p>Its <strong>time complexity</strong> is impressive!<br>In this blog, you will gain a thorough understanding of Merge Sort and try out fun activities to get hands-on with this amazing problem-solving algorithm.<br>Without further ado, let&#x2019;s dive in and learn all about Merge Sort!</p><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><h2 id="merge-sort%E2%80%99s-divide-and-conquer-algorithm-design">Merge Sort&#x2019;s Divide and Conquer Algorithm Design</h2><p><strong>Divide and conquer</strong> is a popular algorithm design technique where a huge or cumbersome problem is broken down into simpler, solvable subproblems. The solutions of the subproblems are combined to solve the original problem.<br>Let us see how this logic is applied in Merge Sort!<br>You would have come across Merge Sort examples in the following way:</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/09/Merge-sort-algorithm.png" class="kg-image" alt="Everything You Need To Know About Merge Sort" loading="lazy" width="1920" height="1279" srcset="https://www.crio.do/blog/content/images/size/w600/2021/09/Merge-sort-algorithm.png 600w, https://www.crio.do/blog/content/images/size/w1000/2021/09/Merge-sort-algorithm.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2021/09/Merge-sort-algorithm.png 1600w, https://www.crio.do/blog/content/images/2021/09/Merge-sort-algorithm.png 1920w" sizes="(min-width: 720px) 720px"></figure><p>Although this is the big picture, it does not clearly define how the recursive calls occur.</p><p>Take a look at the pseudocode:</p><!--kg-card-begin: html--><pre>
<code>
Mergesort (A[0..n-1])
//Input: An array A[0..n-1]
//Output: Array A[0..n-1] sorted in increasing order

//If the array contains just one element, or if it is empty, it is already sorted
If n &lt; 2
	return
else
    //copy first half of the array A to an array B
    copy A[0..floor(n/2) - 1] to B[0..floor(n/2) - 1] 
    //copy second half of the array A to an array C
    copy A[floor(n/2)..n - 1] to C[0..floor(n/2) - 1]
    //recursively divide array B until base case is reached 
    Mergesort(B[0..floor(n/2) - 1)
    //recursively divide array C until base case is reached
    Mergesort(C[0..floor(n/2) - 1)
    //Merge sorted arrays B and C back into A 
    Merge (B,C,A)
</code>
</pre><!--kg-card-end: html--><p>In Merge Sort, you must keep splitting the array until you reach the base case. That is, until you have only one item. One item is considered to be a sorted array.<br>An empty array also falls under the base case. It is sorted.</p><h3 id="recursion">Recursion</h3><p>Merge Sort has a recursive function that splits the array recursively until the base case is reached.</p><h3 id="merge-subroutine">Merge subroutine</h3><p>It also has a merge subroutine that compares each element in two arrays, at every level of division, sorts, and then merges them.<br>Notice the operation &#x2018;floor&#x2019; in the pseudocode. This is to make sure that Merge Sort works for an odd number of input sizes as well. (Ex: floor(5.4) = 5)</p><h2 id="tracing-the-flow-of-merge-sort">Tracing the flow of Merge Sort</h2><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/09/Merge-sort-step-1.png" class="kg-image" alt="Everything You Need To Know About Merge Sort" loading="lazy" width="1535" height="881" srcset="https://www.crio.do/blog/content/images/size/w600/2021/09/Merge-sort-step-1.png 600w, https://www.crio.do/blog/content/images/size/w1000/2021/09/Merge-sort-step-1.png 1000w, https://www.crio.do/blog/content/images/2021/09/Merge-sort-step-1.png 1535w" sizes="(min-width: 720px) 720px"></figure><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/09/Merge-sort-step-2.png" class="kg-image" alt="Everything You Need To Know About Merge Sort" loading="lazy" width="1535" height="1087" srcset="https://www.crio.do/blog/content/images/size/w600/2021/09/Merge-sort-step-2.png 600w, https://www.crio.do/blog/content/images/size/w1000/2021/09/Merge-sort-step-2.png 1000w, https://www.crio.do/blog/content/images/2021/09/Merge-sort-step-2.png 1535w" sizes="(min-width: 720px) 720px"></figure><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/09/MERGE-SORT-STEP-3.png" class="kg-image" alt="Everything You Need To Know About Merge Sort" loading="lazy" width="1462" height="764" srcset="https://www.crio.do/blog/content/images/size/w600/2021/09/MERGE-SORT-STEP-3.png 600w, https://www.crio.do/blog/content/images/size/w1000/2021/09/MERGE-SORT-STEP-3.png 1000w, https://www.crio.do/blog/content/images/2021/09/MERGE-SORT-STEP-3.png 1462w" sizes="(min-width: 720px) 720px"></figure><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/09/MERGE-SORT-STEP-4.png" class="kg-image" alt="Everything You Need To Know About Merge Sort" loading="lazy" width="1535" height="1087" srcset="https://www.crio.do/blog/content/images/size/w600/2021/09/MERGE-SORT-STEP-4.png 600w, https://www.crio.do/blog/content/images/size/w1000/2021/09/MERGE-SORT-STEP-4.png 1000w, https://www.crio.do/blog/content/images/2021/09/MERGE-SORT-STEP-4.png 1535w" sizes="(min-width: 720px) 720px"></figure><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/09/MERGE-SORT-STEP-5.png" class="kg-image" alt="Everything You Need To Know About Merge Sort" loading="lazy" width="1535" height="1204" srcset="https://www.crio.do/blog/content/images/size/w600/2021/09/MERGE-SORT-STEP-5.png 600w, https://www.crio.do/blog/content/images/size/w1000/2021/09/MERGE-SORT-STEP-5.png 1000w, https://www.crio.do/blog/content/images/2021/09/MERGE-SORT-STEP-5.png 1535w" sizes="(min-width: 720px) 720px"></figure><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/09/MERGE-SORT-STEP-6.png" class="kg-image" alt="Everything You Need To Know About Merge Sort" loading="lazy" width="1462" height="764" srcset="https://www.crio.do/blog/content/images/size/w600/2021/09/MERGE-SORT-STEP-6.png 600w, https://www.crio.do/blog/content/images/size/w1000/2021/09/MERGE-SORT-STEP-6.png 1000w, https://www.crio.do/blog/content/images/2021/09/MERGE-SORT-STEP-6.png 1462w" sizes="(min-width: 720px) 720px"></figure><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/09/MERGE-SORT-STEP-7.png" class="kg-image" alt="Everything You Need To Know About Merge Sort" loading="lazy" width="1462" height="651" srcset="https://www.crio.do/blog/content/images/size/w600/2021/09/MERGE-SORT-STEP-7.png 600w, https://www.crio.do/blog/content/images/size/w1000/2021/09/MERGE-SORT-STEP-7.png 1000w, https://www.crio.do/blog/content/images/2021/09/MERGE-SORT-STEP-7.png 1462w" sizes="(min-width: 720px) 720px"></figure><h2 id="implementation-of-merge-sort-in-python">Implementation of Merge Sort in Python</h2><!--kg-card-begin: html--><pre>
<code class="language-python">
def merge_sort(array, l_index, r_index):
#recursive function
if l_index &lt; r_index:
    mid = (l_index + r_index)//2
    merge_sort(array, l_index, mid)
    merge_sort(array, mid + 1, r_index)
    merge(array, l_index, r_index, mid)
#merge subroutine

def merge(array, l_index, r_index, mid):
#Merge Sort needs auxiliary space for merging. L_half and r_half are two arrays that #are used to store elements after each comparison made during sorting
l_half = array[l_index:mid + 1]
r_half = array[mid+1:r_index+1]
l_half_index = 0
r_half_index = 0
sorted_index = l_index

#compare sorted left and right subarrays and merge them
while l_half_index &lt; len(l_half) and r_half_index &lt; len(r_half):
    if l_half[l_half_index] <= 1 r_half[r_half_index]: array[sorted_index]="l_half[l_half_index]" l_half_index="l_half_index" + else: r_half_index="r_half_index" sorted_index="sorted_index" #there could be elements still left after each comparison has been made for i in range(l_half_index,len(l_half)): range(r_half_index,len(r_half)): merge_sort(array, 0, len(array) -1) print(array) < code>
</=></code></pre><!--kg-card-end: html--><h3 id="input">Input</h3><p>array = [33,1,60,14,16,1,800]</p><h3 id="output">Output<br></h3><p>[1, 1, 14, 16, 33, 60, 800]</p><h3 id="test-your-understanding">Test your understanding</h3><p><strong>Q1</strong> Given the following list of numbers, [80, 1, 40, 22, 10, 11, 70, 13, 2, 13, 10, 65, 13, 15, 16, 7] which answer illustrates the list to be sorted, after three recursive calls to merge_sort?</p><ol><li>[2, 13, 10, 65, 13, 15, 16, 7]</li><li>[80,1]</li><li>[80, 1, 40, 22]</li><li>[80]</li></ol><p><strong>Q2</strong> Given the following list of numbers, [80, 1, 40, 22, 10, 11, 70, 13, 2, 13, 10, 65, 13, 15, 16, 7] which answer illustrates the first two lists to be merged?</p><ol><li>[80, 1] and [40, 22]</li><li>[1, 10, 11, 13, 22, 40, 80] and [2, 7, 10, 13, 13, 15, 16, 65]</li><li>[80] and [1]</li><li>[2] and [7]</li></ol><p><strong>Q3</strong> What would be the first left split of the array [8, 1, 5, 10, 11, 2, 6] according to the pseudocode we saw earlier?</p><ol><li>[8, 1, 5]</li><li>[8, 1, 5, 10]</li></ol><h2 id="time-complexity-analysis-of-merge-sort">Time Complexity Analysis of Merge Sort</h2><p>How does Merge Sort have &#x398;(n*logn) time complexity?</p><p>Firstly, Merge Sort makes n - 1 comparisons during sorting. For example, consider two arrays</p><p>[1, 3] and [2, 4]</p><p>Compare 1 with 2. 1 &lt; 2, hence 1 is added into the array.</p><p>Compare 3 with 2. 2 &lt; 3, hence 2 is added into the array.</p><p>Compare 3 with 4. 3 &lt; 4, hence 3 is added into the array.</p><p>4 is the only element left, it is added into the array.</p><p>Now, you &#xA0;have n - 1 comparisons.</p><p>Consider an input of size n = 8</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/09/MERGE-SORT.png" class="kg-image" alt="Everything You Need To Know About Merge Sort" loading="lazy" width="1920" height="1232" srcset="https://www.crio.do/blog/content/images/size/w600/2021/09/MERGE-SORT.png 600w, https://www.crio.do/blog/content/images/size/w1000/2021/09/MERGE-SORT.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2021/09/MERGE-SORT.png 1600w, https://www.crio.do/blog/content/images/2021/09/MERGE-SORT.png 1920w" sizes="(min-width: 720px) 720px"></figure><p>The figure above demonstrates that for an input size of 8, three levels of division are needed. Thus the number of levels of division is log2(8) = 3<br>Writing log as a function of n, we get log2(n).<br>For n = 2k if you keep dividing further, at each level, you can generalize the above calculations as &#x2211; 2k[n/2k-1] with lower bound as k = 0 and upper bound as log(n) - 1<br>It results in <strong>&#x398;(n*logn)</strong><br><strong>Worst case:</strong> Assume for the sake of simplicity, that n is a power of 2. Let C(n) be the number of key comparisons made. The equation below defines the amount of work that needs to be done to divide and merge the arrays.<br>C(n) = 2C(n/2) + Cmerge (n)<br>C(n/2) is the number of comparisons at each left and right split.<br>C(1) = 0 (For just one element no comparisons are made)<br>Cmerge (n) represents the number of comparisons made while merging.<br>At each step, exactly one comparison is made, after which, the total number of elements in the two arrays still needed to be compared is reduced by one.<br>In the worst case, neither of the two arrays becomes empty, before the other one contains just one element.<br>Hence, for the worst case, Cmerge (n) is n - 1<br>An example of an array that would be the worst case scenario for Merge Sort is [1, 9, 5, 13, 3, 11, 7, 15]..<br>Cworst(n) = 2Cworst(n/2) + n - 1<br>Using master&#x2019;s theorem, you can conclude that<br>Cworst(n) = nlog2n + n - 1<br><strong>Best case:</strong> In the best case scenario, the array is already sorted, but we still have to split and recombine it back.</p><h2 id="time-complexity-curve-plot-using-python">Time complexity curve plot using Python</h2><p>The merge_sort function that we wrote previously, is used to plot the curve for random input.<br>Python&#x2019;s random module is used to generate random numbers as input.<br>Time module is used to measure how much time was taken for merge_sort to finish execution. Here we plot a graph of Input size against Time taken.<br></p><!--kg-card-begin: html--><pre>
<code>
import time
from random import randint

arr1 = [randint(0,1000) for i in range(10000)]
times=[]

for x in range(0,10000,100):
    start_time = time.time()
    arr2 = (arr1[:x])
    merge_sort(list2,0, len(arr2)-1)
    elapsed_time = time.time() - start_time
    times.append(elapsed_time)
    elapsed_time
x=[i for i in range(0,10000,100)]

import matplotlib.pyplot as plt
%matplotlib inline
plt.xlabel(&quot;No. of elements&quot;)
plt.ylabel(&quot;Time required&quot;)
plt.plot(x,times)
</code>
</pre><!--kg-card-end: html--><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/09/Merge-sort-time-complexity.png" class="kg-image" alt="Everything You Need To Know About Merge Sort" loading="lazy" width="1847" height="1406" srcset="https://www.crio.do/blog/content/images/size/w600/2021/09/Merge-sort-time-complexity.png 600w, https://www.crio.do/blog/content/images/size/w1000/2021/09/Merge-sort-time-complexity.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2021/09/Merge-sort-time-complexity.png 1600w, https://www.crio.do/blog/content/images/2021/09/Merge-sort-time-complexity.png 1847w" sizes="(min-width: 720px) 720px"></figure><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/09/Insertion-sort-time-complexity.png" class="kg-image" alt="Everything You Need To Know About Merge Sort" loading="lazy" width="1847" height="1499" srcset="https://www.crio.do/blog/content/images/size/w600/2021/09/Insertion-sort-time-complexity.png 600w, https://www.crio.do/blog/content/images/size/w1000/2021/09/Insertion-sort-time-complexity.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2021/09/Insertion-sort-time-complexity.png 1600w, https://www.crio.do/blog/content/images/2021/09/Insertion-sort-time-complexity.png 1847w" sizes="(min-width: 720px) 720px"></figure><p>Selection Sort&#x2019;s time complexity clearly appears to be quadratic. For larger values of input size, Merge Sort&#x2019;s time complexity curve can be enhanced.</p><h2 id="take-a-deeper-look-at-merge-sort">Take a deeper look at Merge Sort</h2><p>Analysis of <strong>sorting algorithms</strong> needs three things to be considered. They are <strong>time complexity</strong>, <strong>space complexity</strong>, and <strong>stability</strong>.<br><br><strong>Time complexity</strong><br>Merge Sort has an efficient <strong>time complexity</strong> of <strong>&#x398;(n*logn)</strong>. But, quicksort is still faster, as long as a random pivot is chosen.</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/09/Merge-sort-time-complexity-curve.png" class="kg-image" alt="Everything You Need To Know About Merge Sort" loading="lazy" width="1847" height="1398" srcset="https://www.crio.do/blog/content/images/size/w600/2021/09/Merge-sort-time-complexity-curve.png 600w, https://www.crio.do/blog/content/images/size/w1000/2021/09/Merge-sort-time-complexity-curve.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2021/09/Merge-sort-time-complexity-curve.png 1600w, https://www.crio.do/blog/content/images/2021/09/Merge-sort-time-complexity-curve.png 1847w" sizes="(min-width: 720px) 720px"></figure><p><strong>Space complexity</strong><br>Merge Sort, like other <strong>sorting algorithms</strong>, does not work <strong>in-place</strong>.<br>An <strong>in-place algorithm</strong> is a <strong>sorting algorithm</strong> in which the sorted items occupy the same storage as the original ones.<br>But Merge Sort makes copies of the left and right half of the given array. It requires a linear amount of extra storage space, <strong>&#x398;(n)</strong>.<br><br><strong>Stability</strong><br>Merge Sort is a <strong>stable algorithm</strong>. An algorithm is said to be <strong>stable</strong> when it keeps elements with equal values in the same relative order in the output as they were originally, in the input.</p><hr><p>The efficiency of Merge Sort, apart from it having a great time complexity, is that you don&apos;t need to read all the data in memory at once. Because of the divide-and-conquer nature of the algorithm, it can be easily parallelized. </p><h2 id="applications-of-merge-sort">Applications of Merge Sort</h2><h3 id="sorting-linked-lists">Sorting linked lists</h3><p>You have seen merge sort being implemented using arrays. However, in practice merge sort works better with linked lists. This is because you don&#x2019;t have to store elements linearly in linked lists.</p><p>Items to a linked list can be inserted in the middle in &#x398;(1) extra space and &#x398;(1) time. Hence, merge sort is more efficient when linked lists are used.</p><h3 id="counting-inversions-in-an-array">Counting inversions in an array</h3><p>Inversion counting is about checking how far, or close an array is from being sorted.</p><p>E- commerce websites have a section - &quot;You might like.&#x201D;</p><p>To display the options under this, they maintain an array for all the user accounts.</p><p>Merge sort helps to check the least number of inversions count with your array of choices. Based on this, they will recommend to you about what other users bought or liked.</p><h3 id="external-sorting">External Sorting</h3><p>In practice, enormous amounts of data is processed. Sorting such huge amounts of data needs additional, external memory. Usually an external hard drive is used, when data does not fit in memory. When implementing External Sorting, merge sort plays a crucial role.</p><h3 id="test-your-understanding-1">Test your understanding</h3><p><strong>Q4</strong> Merge Sort requires an auxiliary space of</p><ol><li>&#x398;(1)</li><li>&#x398;(n)</li></ol><p><strong>Q5 </strong>The input size of the array to be sorted with Merge Sort is 9. How many levels of division does Merge Sort do?</p><p><strong>Q6</strong> Say you have two sorted lists of size m and n. The number of comparisons in the worst case by the Merge Sort algorithm will be</p><ol><li>m x n</li><li>m + n</li><li>m + n - 1</li></ol><h3 id="try-it-yourself">Try it yourself</h3><ol><li>Apply Merge Sort to sort the list L, E, A, R, N, B, Y, D, O, I, N, G in alphabetical order</li><li>Implement Merge Sort using linked lists</li><li>Use python&#x2019;s pygorithm module to learn more about all sorting algorithms. </li></ol><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/insertion-sort/?utm_source=blog-int"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Master Insertion Sort Before Your Next Big Interview</div><div class="kg-bookmark-description">Learn the details of insertion sort and how you can use it effectively to sort your dataset</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="Everything You Need To Know About Merge Sort"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Harshita Bansal</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/08/Insertion-sort.png" alt="Everything You Need To Know About Merge Sort"></div></a></figure><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure>]]></content:encoded></item><item><title><![CDATA[10 Best Sorting Algorithms You Must Know About]]></title><description><![CDATA[What is the fastest sorting algorithm? Which one is the simplest sorting algorithm? Why do we even use sorting algorithms? Get all your answers.]]></description><link>https://www.crio.do/blog/top-10-sorting-algorithms-2024/</link><guid isPermaLink="false">66c783bc134c11095afa92f0</guid><category><![CDATA[Data Structures and Algorithms]]></category><category><![CDATA[Crio Community]]></category><dc:creator><![CDATA[Sandipan Das]]></dc:creator><pubDate>Thu, 08 Aug 2024 05:02:00 GMT</pubDate><media:content url="https://www.crio.do/blog/content/images/2022/02/Sorting-Algorithms.png" medium="image"/><content:encoded><![CDATA[<img src="https://www.crio.do/blog/content/images/2022/02/Sorting-Algorithms.png" alt="10 Best Sorting Algorithms You Must Know About"><p></p><hr><!--kg-card-begin: markdown--><h3 id="before-you-begin">Before you begin..</h3>
<!--kg-card-end: markdown--><p>Try giving a shot at common MAANG Sorting Algorithms Interview Questions before reading the blog.</p><!--kg-card-begin: html--><a href="https://www.crio.do/learn/v2/magic/sorting-quiz-1/?utm_source=crio-blog&amp;utm_medium=tsa" class="btn">Answer MAANG Interview Questions</a><!--kg-card-end: html--><!--kg-card-begin: markdown--><h3 id="after-you-read-the-blog">After you read the blog..</h3>
<!--kg-card-end: markdown--><p>Answer more advanced questions to be absolutely interview-ready. Check out the quiz at the end. Read this blog to get a perfect score in that quiz :)</p><hr><p>The arrangement of data in a specific order (ascending or descending) is termed <strong>sorting</strong> in <strong>data structures</strong>. <strong>Sorting</strong> data makes it easier to search through a given data sample, efficiently and quickly.</p><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><h2 id="why-are-sorting-algorithms-important">Why are Sorting Algorithms Important?</h2><p>Since <strong>sorting</strong> can often help reduce the <strong>algorithmic complexity</strong> of a problem, it finds significant uses in computer science.<br>A quick Google search reveals that there are over 40 different <strong>sorting algorithms</strong> used in the computing world today. Crazy right?<br>Well, you will be flabbergasted when you realize just how useful <strong>sorting algorithms</strong> are in real life. Some of the best examples of real-world implementation of the same are:<br>- Bubble sorting is used in programming TV to sort channels based on audience viewing time!<br>- Databases use external merge sort to sort sets of data that are too large to be loaded entirely into memory!<br>- Sports scores are quickly organized by quick sort algorithm in real-time!!</p><hr><p><em>How well do you know your sorting algorithms? <a href="https://www.crio.do/learn/v2/magic/sorting-quiz-1/?utm_source=crio-blog&amp;utm_medium=tsa">Take this quiz to find out &gt;&gt; </a></em></p><hr><h2 id="types-of-sorting-in-data-structures">Types of Sorting in Data Structures</h2><p><em>Want to brush up your sorting algorithms before an interview? <a href="https://www.crio.do/learn/v2/magic/sorting-quiz-2/?utm_source=crio-blog&amp;utm_medium=tsa">Answer these questions before you go &gt;&gt; </a></em></p><ul><li><strong>Comparison-based sorting</strong>: In comparison-based <strong>sorting</strong> techniques, a comparator is defined to compare elements or items of a data sample. This comparator defines the ordering of elements. Examples are: <strong>Bubble Sort, <a href="https://www.crio.do/blog/merge-sort-algorithm/?utm_source=blog-int">Merge Sort</a>.</strong></li><li><strong>Counting-based sorting</strong>: There&apos;s no comparison involved between elements in these types of <strong>sorting algorithms</strong> but rather work on calculated assumptions during execution. Examples are : <strong>Counting Sort</strong>, <strong>Radix Sort</strong>.</li><li><strong>In-Place vs Not-in-Place Sorting:</strong> In-place <strong>sorting</strong> techniques in <strong>data structures</strong> modify the ordering of array elements within the original array. On the other hand, Not-in-Place <strong>sorting</strong> techniques use an auxiliary data structure to sort the original array. Examples of In place <strong>sorting</strong> techniques are: <strong>Bubble Sort</strong>, <strong>Selection Sort</strong>. Some examples of Not in Place <strong>sorting algorithms</strong> are: <strong>Merge Sort</strong>, <strong>Quick Sort</strong>.</li></ul><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/merge-sort-algorithm/?utm_source=blog-int"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Everything You Need To Know About Merge Sort</div><div class="kg-bookmark-description">Learn the fundamentals of Merge Sort with an example. Sharpen your understanding with fun quizzes and activities.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="10 Best Sorting Algorithms You Must Know About"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Abheetha Pradhan</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/09/Merge-sort.png" alt="10 Best Sorting Algorithms You Must Know About"></div></a></figure><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/quick-sort/?utm_source=blog-int"><div class="kg-bookmark-content"><div class="kg-bookmark-title">The Complete Quick Sort Guide</div><div class="kg-bookmark-description">Learn the fundamentals of Quick Sort with an example. Sharpen your understanding with fun quizzes and activities</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="10 Best Sorting Algorithms You Must Know About"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Abheetha Pradhan</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/11/Quick-Sort.png" alt="10 Best Sorting Algorithms You Must Know About"></div></a></figure><p>This article will enable your problem solving skills with the <strong>Top 10 Sorting Algorithms</strong> used in the computing world today including bubble sort and <a href="https://www.crio.do/blog/merge-sort-algorithm/?utm_source=blog-int">merge sort algorithms</a>. </p><p>You will also be diving deep into the working of various sorting techniques with intuitive examples covering <a href="https://www.crio.do/blog/time-complexity-explained/?utm_source=blog-int">time and space complexities</a> in best and worst-case scenarios. </p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/time-complexity-explained/?utm_source=blog-int"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Time Complexity Simplified with Easy Examples</div><div class="kg-bookmark-description">Find out what is time complexity. Understand how to analyze time complexities with simple examples.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="10 Best Sorting Algorithms You Must Know About"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Sandipan Das</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/08/time-complexity-of-sorting-algorithms.png" alt="10 Best Sorting Algorithms You Must Know About"></div></a></figure><p>Finally, we&apos;ll wrap up with a broad-spectrum analysis as to which algorithm stands out in terms of time and space complexities.</p><h3 id="sorting-algorithms-in-java-vs-c">Sorting Algorithms in Java vs C++</h3><p><strong>Java</strong> is the most popular language of choice when it comes to implementing algorithms and working with <strong>data structures</strong> in the software industry.</p><hr><p>Level up your foundational programming skills in Java and practice the most relevant Data Structure questions in Crio&apos;s Backend Developer Program. <a href="https://www.crio.do/backend-developer-track/?utm_source=crio-blog&amp;utm_medium=tsa&amp;utm_campaign=xxxxx#java-essentials"><strong>Check out the full syllabus here &gt;&gt; </strong></a></p><hr><p>Although this blog focuses heavily on C++ based implementations, don&apos;t fret because as long as your logical understanding of these algorithms is strong, the only thing holding you back is basic syntactic differences between <strong>Java</strong> and <strong>C++</strong>.</p><hr><p>Want to build your foundations of Java concepts? <a href="https://www.crio.do/bytes/?utm_source=crio-blog&amp;utm_medium=tsa&amp;utm_campaign=xxxxx#java-concepts"><strong>Check out these free immersive activities on Crio&apos;s learning platform &gt;&gt;</strong></a></p><hr><p>So without further ado, let&apos;s dive right in.</p><hr><h3 id="need-guidance-with-problem-solving-and-data-structures-go-through-crios-data-structures-track-and-unlock-what-it-takes-to-tackle-unseen-problems-with-ease"><strong><strong>Need guidance with problem-solving and data structures? Go through </strong><a href="https://www.crio.do/software-development-fellowship-program/?utm_source=crio-blog&amp;utm_medium=tsa&amp;utm_campaign=xxxxx#data-structures"><strong>Crio&apos;s Data Structures Track</strong></a><strong> and unlock what it takes to tackle unseen problems with ease.</strong></strong> &#xA0;</h3><hr><h2 id="top-10-sorting-algorithms-you-need-to-know">Top 10 Sorting Algorithms You Need To Know</h2><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://www.crio.do/blog/content/images/2022/01/Top-10-Sorting-Algorithms-You-Need-To-Know.png" class="kg-image" alt="10 Best Sorting Algorithms You Must Know About" loading="lazy" width="1366" height="4096" srcset="https://www.crio.do/blog/content/images/size/w600/2022/01/Top-10-Sorting-Algorithms-You-Need-To-Know.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/01/Top-10-Sorting-Algorithms-You-Need-To-Know.png 1000w, https://www.crio.do/blog/content/images/2022/01/Top-10-Sorting-Algorithms-You-Need-To-Know.png 1366w" sizes="(min-width: 720px) 720px"><figcaption>10 Best Sorting Algorithms</figcaption></figure><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><h2 id="1-bubble-sort">1. Bubble Sort</h2><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/12/Bubble-Sort-2.gif" class="kg-image" alt="10 Best Sorting Algorithms You Must Know About" loading="lazy" width="1212" height="1026"></figure><p>The basic idea of <strong>bubble sorting</strong> is that it repeatedly swaps adjacent elements if they are not in the desired order. YES, it is as simple as that.<br>If a given array of elements has to be sorted in ascending order, <strong>bubble sorting</strong> will start by comparing the first element of the array with the second element and immediately swap them if it turns out to be greater than the second element, and then move on to compare the second and third element, and so on.</p><h3 id="understanding-bubble-sort-algorithm-with-a-simple-example">Understanding Bubble Sort algorithm with a simple example</h3><p>Let&apos;s try to understand the intuitive approach behind bubble sort with an example:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://www.crio.do/blog/content/images/2022/01/Bubble-sort-algorithm-example-1.png" class="kg-image" alt="10 Best Sorting Algorithms You Must Know About" loading="lazy" width="1920" height="1340" srcset="https://www.crio.do/blog/content/images/size/w600/2022/01/Bubble-sort-algorithm-example-1.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/01/Bubble-sort-algorithm-example-1.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/01/Bubble-sort-algorithm-example-1.png 1600w, https://www.crio.do/blog/content/images/2022/01/Bubble-sort-algorithm-example-1.png 1920w" sizes="(min-width: 720px) 720px"><figcaption>Bubble sort algorithm explained</figcaption></figure><p>Now that you&apos;ve understood the intuitive idea behind bubble sort, it&apos;s time to take a look at its standard C++ implementation.</p><p><strong>Implementation in C++</strong></p><figure class="kg-card kg-code-card"><pre><code class="language-C++">#include &lt;bits/stdc++.h&gt;
using namespace std;

void Bubble_Sort(int vec[], int n){
	int i, j;
	for (i = 0; i &lt; n-1; i++)
	for (j = 0; j &lt; n-i-1; j++)
		if (vec[j] &gt; vec[j+1])
			swap(vec[j], vec[j+1]);
}
int main(){
	int vec[] = {5, 3, 4, 2, 1};
	int n = sizeof(vec)/sizeof(vec[0]);
	Bubble_Sort(vec, n);
	cout&lt;&lt;&quot;Sorted array: \n&quot;;
	for (int i = 0; i &lt; n; i++)
		cout &lt;&lt; vec[i] &lt;&lt; &quot; &quot;;
	cout &lt;&lt; endl;
}</code></pre><figcaption>Bubble Sorting AlImplementation</figcaption></figure><p><strong>Time Complexity:</strong></p><ul><li><em>Worst Case:</em> O(n^2)</li><li><em>Average Case</em>: O(n*logn)</li><li><em>Best case</em>: O(n*logn)</li></ul><p><strong>Auxiliary Space Complexity:</strong> O(1)</p><p>Also read: <a href="https://www.crio.do/blog/time-complexity-explained/?utm_source=blog-int">Time Complexity Simplified with Easy Examples</a></p><h3 id="use-cases">Use Cases</h3><ul><li>It is used to introduce the concept of a sorting algorithm to Computer Science students.</li><li>In computer graphics, bubble sorting is quite popular when it comes to detecting a very small error (like swap of just two elements) in almost-sorted arrays.</li></ul><h3 id="try-it-yourself"><u>Try it yourself</u></h3><p>Q. Given an array of n input integers, return the sum of maximum and minimum elements of the array. [Constraint: Use Bubble Sorting]</p><p><strong>Input:</strong></p><ul><li>n -&gt; Size of array (n&gt;1)</li><li>&apos;n&apos; array elements below</li></ul><p><strong>Output: </strong>A single line representing the required sum</p><p><strong>P.S</strong>: Don&apos;t forget to drop a comment below if you face issues with this problem. </p><hr><h2 id="2-selection-sort">2. Selection Sort</h2><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/12/Selection-Sort.gif" class="kg-image" alt="10 Best Sorting Algorithms You Must Know About" loading="lazy" width="958" height="810"></figure><p><strong>Selection sort</strong> is a <strong>sorting algorithm</strong> in which the given array is divided into two subarrays, the sorted left section, and the unsorted right section.<br>Initially, the sorted portion is empty and the unsorted part is the entire list. In each iteration, we fetch the minimum element from the unsorted list and push it to the end of the sorted list thus building our sorted array.<br>Still a bit fuzzy? Take a look at this awesome example below.</p><h3 id="understanding-selection-sort-algorithm-with-an-example">Understanding Selection Sort algorithm with an example</h3><p>Let&apos;s try to understand the intuitive idea behind selection sort with a simple example:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://www.crio.do/blog/content/images/2022/01/Selection-sort-algorithm-example-1.png" class="kg-image" alt="10 Best Sorting Algorithms You Must Know About" loading="lazy" width="1920" height="1510" srcset="https://www.crio.do/blog/content/images/size/w600/2022/01/Selection-sort-algorithm-example-1.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/01/Selection-sort-algorithm-example-1.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/01/Selection-sort-algorithm-example-1.png 1600w, https://www.crio.do/blog/content/images/2022/01/Selection-sort-algorithm-example-1.png 1920w" sizes="(min-width: 720px) 720px"><figcaption>Selection sort algorithm explained</figcaption></figure><p>Seems easy right? Because it is.</p><p>Now go ahead and take a look at its basic C++-based implementation.</p><figure class="kg-card kg-code-card"><pre><code class="language-C++">#include &lt;bits/stdc++.h&gt;
using namespace std;

void Selection_Sort(int vec[], int n){
	int i, j, pos;
	for (i = 0; i &lt; n-1; i++){
		pos = i;
		for (j = i+1; j &lt; n; j++)
		if (vec[j] &lt; vec[pos])
			pos = j;
		swap(vec[pos], vec[i]);
	}
}

int main(){
	int vec[] = {25, 22, 27, 15, 19};
	int n = sizeof(vec)/sizeof(vec[0]);
	Selection_Sort(vec, n);
	cout &lt;&lt; &quot;Sorted array: \n&quot;;
	for (int i=0; i &lt; n; i++)
		cout &lt;&lt; vec[i] &lt;&lt; &quot; &quot;;
	cout &lt;&lt; endl;
	return 0;
}</code></pre><figcaption>Selection Sort Implementation</figcaption></figure><p><strong>Time Complexity:</strong></p><ul><li><em>Worst Case:</em> O(n*n)</li><li><em>Average Case:</em> O(n*logn)</li><li><em>Best case:</em> O(n*logn)</li></ul><p><strong>Auxiliary Space Complexity:</strong> O(1)</p><p><strong>Also read: <a href="https://www.crio.do/blog/time-complexity-explained/?utm_source=blog-int">Time Complexity Simplified with Easy Examples</a></strong></p><h3 id="use-cases-1">Use Cases</h3><ul><li>It is used when the size of a list is small. (<a href="https://www.crio.do/blog/time-complexity-explained/?utm_source=blog-int">Time complexity</a> of selection sort is <strong>O(N^2)</strong> which makes it inefficient for a large list.)</li><li>It is also used when memory space is limited because it makes the minimum possible number of swaps during sorting.</li></ul><h3 id="try-it-yourself-1"><u>Try it yourself</u></h3><p><br>Q. Given an array of n input integers, return the absolute difference between the maximum and minimum elements of the array. [Constraint: Use Selection Sorting]</p><p><strong>Input:</strong></p><ul><li>n -&gt; Size of array (n&gt;1)</li><li>&apos;n&apos; array elements below</li></ul><p><strong>Output: </strong>A single line representing the required difference</p><hr><h3 id="build-5-mini-projects-and-master-essential-data-structures-and-algorithms-you-need-to-crack-your-next-big-tech-interview">Build <a href="https://www.crio.do/software-development-fellowship-program/?utm_source=crio-blog&amp;utm_medium=tsa&amp;utm_campaign=xxxxx#data-structures">5 mini-projects</a> and master essential data structures and algorithms you need to crack your next big tech interview.</h3><hr><h2 id="3-insertion-sort">3. Insertion Sort</h2><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/12/Insertion-Sort.gif" class="kg-image" alt="10 Best Sorting Algorithms You Must Know About" loading="lazy" width="958" height="810"></figure><p><a href="https://www.crio.do/blog/insertion-sort/?utm_source=blog-int"><strong>Insertion sort</strong></a> is a <strong>sorting algorithm</strong> in which the given array is divided into a sorted and an unsorted section. In each iteration, the element to be inserted has to find its optimal position in the sorted subsequence and is then inserted while shifting the remaining elements to the right.</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/insertion-sort/?utm_source=blog-int"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Master Insertion Sort Before Your Next Big Interview</div><div class="kg-bookmark-description">Learn the details of insertion sort and how you can use it effectively to sort your dataset</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="10 Best Sorting Algorithms You Must Know About"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Harshita Bansal</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/08/Insertion-sort.png" alt="10 Best Sorting Algorithms You Must Know About"></div></a></figure><h3 id="understanding-insertion-sort-algorithm-with-an-example">Understanding Insertion Sort algorithm with an example</h3><p>Here&apos;s an example to help you understand insertion sort better:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://www.crio.do/blog/content/images/2022/01/Insertion-sort-algorithm-example-1.png" class="kg-image" alt="10 Best Sorting Algorithms You Must Know About" loading="lazy" width="1920" height="1205" srcset="https://www.crio.do/blog/content/images/size/w600/2022/01/Insertion-sort-algorithm-example-1.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/01/Insertion-sort-algorithm-example-1.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/01/Insertion-sort-algorithm-example-1.png 1600w, https://www.crio.do/blog/content/images/2022/01/Insertion-sort-algorithm-example-1.png 1920w" sizes="(min-width: 720px) 720px"><figcaption>Insertion sort algorithm explained</figcaption></figure><p>Now that you&apos;ve understood how insertion sorting actually works, take a look at its standard C++ implementation.</p><figure class="kg-card kg-code-card"><pre><code class="language-C++">#include &lt;bits/stdc++.h&gt;
using namespace std;

void Insertion_Sort(int vec[], int n){
	int i, x, j;
	for (i = 1; i &lt; n; i++){
		x = vec[i];
		j = i - 1;
		while (j &gt;= 0 &amp;&amp; vec[j] &gt; x){
			vec[j + 1] = vec[j];
			j = j - 1;
		}
		vec[j + 1] = x;
	}
}

int main(){
	int vec[] = { 25, 22, 27, 15, 19 };
	int n = sizeof(vec) / sizeof(vec[0]);
	Insertion_Sort(vec, n);
	for (int i = 0; i &lt; n; i++)
		cout &lt;&lt; vec[i] &lt;&lt; &quot; &quot;;
	return 0;
}</code></pre><figcaption>Insertion Sort Implementation</figcaption></figure><p><strong>Time Complexity:</strong></p><ul><li><em>Worst Case:</em> O(n*n)</li><li><em>Average Case:</em> O(n*logn)</li><li><em>Best case:</em> O(n*logn)</li></ul><p><strong>Auxiliary Space Complexity:</strong> O(1)</p><h3 id="use-cases-2">Use Cases</h3><ul><li>This algorithm is stable and is quite fast when the list is nearly sorted.</li><li>It is very efficient when it comes to sorting very small lists (example say 30 elements.)</li></ul><h3 id="try-it-yourself-2"><u>Try it yourself</u></h3><p>Q. Given a list of numbers with an <strong>odd</strong> number of elements, find the <a href="https://en.wikipedia.org/wiki/Median">median</a>? [Constraint: Use Insertion Sort]</p><p><strong>Input:</strong></p><ul><li>n -&gt; Size of array (n&gt;0)</li><li>&apos;n&apos; array elements below</li></ul><p><strong>Output: </strong>A single line representing the required median.</p><p><strong>P.S</strong>: Don&apos;t forget to share your approach with us in the comments below!</p><hr><h2 id="4-quick-sort">4. Quick Sort</h2><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/12/Quick-Sort-1.gif" class="kg-image" alt="10 Best Sorting Algorithms You Must Know About" loading="lazy" width="958" height="810"></figure><p><a href="https://www.crio.do/blog/quick-sort/?utm_source=blog-int"><strong>Quick Sort</strong></a> is a divide and conquer algorithm. The intuitive idea behind <strong>quick sort</strong> is it picks an element as the pivot from a given array of elements and then partitions the array around the pivot element. Subsequently, it calls itself recursively and partitions the two subarrays thereafter.</p><h3 id="understanding-quick-sort-algorithm-with-a-visualization">Understanding Quick Sort algorithm with a visualization</h3><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://www.crio.do/blog/content/images/2022/01/Quick-Sort-Algorithm-flow.png" class="kg-image" alt="10 Best Sorting Algorithms You Must Know About" loading="lazy" width="2000" height="1361" srcset="https://www.crio.do/blog/content/images/size/w600/2022/01/Quick-Sort-Algorithm-flow.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/01/Quick-Sort-Algorithm-flow.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/01/Quick-Sort-Algorithm-flow.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/01/Quick-Sort-Algorithm-flow.png 2400w" sizes="(min-width: 720px) 720px"><figcaption>Quick sort algorithm explained</figcaption></figure><p>The logical steps involved in Quick Sort algorithm are as follows:</p><ul><li><strong>Pivot selection:</strong> Picks an element as the pivot (here, we choose the last element as the pivot)</li><li><strong>Partitioning:</strong> The array is partitioned in a fashion such that all elements less than the pivot are in the left subarray while all elements strictly greater than the pivot element are stored in the right subarray.</li><li><strong>Recursive call to Quicksort:</strong> Quicksort function is invoked again for the two subarrays created above and steps are repeated.</li></ul><p><br>Comments have been included in the implementation below to help you understand the Quick Sort algorithm better.</p><figure class="kg-card kg-code-card"><pre><code class="language-C++">#include &lt;bits/stdc++.h&gt;
using namespace std;
 
int partition (int vec[], int lt, int rt){
	int pivot = vec[rt]; // pivot
	int i = (lt - 1);
	for (int j = lt; j &lt;= rt - 1; j++){
		if (vec[j] &lt; pivot){
			i++; swap(vec[i], vec[j]);
		}
	}
	swap(vec[i + 1], vec[rt]);
	return (i + 1);
}
 
/* vec[] --&gt; array to be sorted,
lt --&gt; Starting index,
rt --&gt; Ending index*/
void Quick_Sort(int vec[], int lt, int rt){
	if (lt &lt; rt){
		/* mid is partitioning index, vec[p] is now
		at right place */
		int mid = partition(vec, lt, rt);
		// Separately sort elements before
		// partition and after partition
		Quick_Sort(vec, lt, mid - 1);
		Quick_Sort(vec, mid + 1, rt);
	}
}
 
int main(){
	int vec[] = {14, 21, 5, 2, 3, 19};
	int n = sizeof(vec) / sizeof(vec[0]);
	Quick_Sort(vec, 0, n - 1);
	cout &lt;&lt; &quot;Sorted array: &quot;;
	for (int i = 0; i &lt; n; i++)
		cout &lt;&lt; vec[i] &lt;&lt; &quot; &quot;;
	return 0;
}</code></pre><figcaption>Quick Sort Implementation</figcaption></figure><p><strong>Time Complexity:</strong></p><ul><li><em>Worst Case:</em> O(n*n)</li><li><em>Average Case:</em> O(n*logn)</li><li><em>Best case:</em> O(n*logn)</li></ul><p><strong>Auxiliary Space Complexity:</strong> O(1)</p><h3 id="use-cases-3">Use Cases</h3><ul><li>Quick Sort is probably more effective for datasets that fit in memory.</li><li>Quick Sort is appropriate for arrays since is an in-place sorting algorithm (i.e. it doesn&#x2019;t require any extra storage)</li></ul><h3 id="try-it-yourself-3"><u>Try it yourself</u></h3><p>Q. Given a list of numbers with an <strong>odd/even</strong> number of elements, find the <a href="https://en.wikipedia.org/wiki/Median">median</a>? [Constraint: Use Quick Sort]</p><p><strong>Input:</strong></p><ul><li>n -&gt; Size of array (n&gt;0)</li><li>&apos;n&apos; array elements below</li></ul><p><strong>Output: </strong>A single line representing the required median.</p><p><strong>P.S</strong>: Need a hint? Drop a comment below.</p><hr><h2 id="5-merge-sort">5. Merge Sort</h2><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/12/Merge-Sort.gif" class="kg-image" alt="10 Best Sorting Algorithms You Must Know About" loading="lazy" width="958" height="810"></figure><p><a href="https://www.crio.do/blog/merge-sort-algorithm/?utm_source=blog-int"><strong>Merge Sort</strong></a> is a divide-and-conquer algorithm. In each iteration, <strong>merge sort</strong> divides the input array into two equal subarrays, calls itself recursively for the two subarrays, and finally merges the two sorted halves.</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/merge-sort-algorithm/?utm_source=blog-int"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Everything You Need To Know About Merge Sort</div><div class="kg-bookmark-description">Learn the fundamentals of Merge Sort with an example. Sharpen your understanding with fun quizzes and activities.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="10 Best Sorting Algorithms You Must Know About"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Abheetha Pradhan</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/09/Merge-sort.png" alt="10 Best Sorting Algorithms You Must Know About"></div></a></figure><h3 id="understanding-merge-sort-algorithm-with-a-visualization">Understanding Merge Sort algorithm with a visualization</h3><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://www.crio.do/blog/content/images/2022/01/Merge-sort-algorithm-flow.png" class="kg-image" alt="10 Best Sorting Algorithms You Must Know About" loading="lazy" width="2000" height="1723" srcset="https://www.crio.do/blog/content/images/size/w600/2022/01/Merge-sort-algorithm-flow.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/01/Merge-sort-algorithm-flow.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/01/Merge-sort-algorithm-flow.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/01/Merge-sort-algorithm-flow.png 2400w" sizes="(min-width: 720px) 720px"><figcaption>Merge sort algorithm explained</figcaption></figure><p>Now that you&apos;re familiar with the intuition behind merge sort, let&apos;s take a look at its implementation.</p><figure class="kg-card kg-code-card"><pre><code class="language-C++">#include &lt;bits/stdc++.h&gt;
using namespace std;

void merge(long vec[], long lt, long m, long rt){
    long n1 = m - lt + 1;
    long n2 = rt - m;
    long L[n1], R[n2];
    for (long i = 0; i &lt; n1; i++)
        L[i] = vec[lt + i];
    for (long j = 0; j &lt; n2; j++) R[j] = vec[m+1+j];
    long i = 0, j = 0;
    long k = lt;
    while (i &lt; n1 and j &lt; n2) {
        if (L[i] &lt;= R[j]) {
            vec[k] = L[i]; i++;
        }
        else {
            vec[k] = R[j]; j++;
        }
        k++;
    }
    while (i &lt; n1) {
        vec[k] = L[i]; i++; k++;
    }
    while (j &lt; n2) {
        vec[k] = R[j]; j++; k++;
    }
}

void Merge_Sort(long vec[],long lt,long rt){
    if(lt&gt;=rt) return;
    long m =lt+ (rt-lt)/2;
    Merge_Sort(vec,lt,m);
    Merge_Sort(vec,m+1,rt);
    merge(vec,lt,m,rt);
}

void printArray(long A[], long size){
    for (long i = 0; i &lt; size; i++)
        cout &lt;&lt; A[i] &lt;&lt; &quot; &quot;;
}
int main(){
    long arr[] = {16, 19, 14, 20, 12, 13};
    long arr_size = sizeof(arr) / sizeof(arr[0]);
    cout &lt;&lt; &quot;Unsorted array is: &quot;;
    printArray(arr, arr_size);
    Merge_Sort(arr, 0, arr_size - 1);
    cout &lt;&lt; &quot;\nSorted array is: &quot;;
    printArray(arr, arr_size);
    return 0;
}</code></pre><figcaption>Merge Sort Implementation</figcaption></figure><p><strong>Time Complexity:</strong></p><ul><li><em>Worst Case:</em> O(n*logn)</li><li><em>Average Case:</em> O(n*logn)</li><li><em>Best case:</em> O(n*logn)</li></ul><p><strong>Auxiliary Space Complexity:</strong> O(n)</p><h3 id="use-cases-4">Use Cases</h3><ul><li>Merge sort is quite fast in the case of linked lists.</li><li>It is widely used for external sorting where random access can be quite expensive compared to sequential access.</li></ul><h3 id="try-it-yourself-4"><u>Try it yourself</u></h3><p>Q. <strong>Find the intersection of two unsorted arrays</strong> [Constraint/Hint: Use Merge Sort]</p><p><strong>Input:</strong></p><ul><li>n -&gt; Size of array (n&gt;1)</li><li>&apos;n&apos; array elements below</li></ul><p><strong>Output: </strong>An array representing the intersection of the two unsorted arrays.</p><hr><h3 id="master-arrays-linked-lists-stacksqueues-trees-and-graphs-and-build-your-career-with-job-guarantee-in-back-end-or-full-stack-development-heres-how">Master Arrays, Linked lists, Stacks/Queues, Trees, and Graphs and build your career (with job guarantee) in Back End or Full Stack development. Here&apos;s <a href="https://www.crio.do/software-development-fellowship-program/?utm_source=crio-blog&amp;utm_medium=tsa&amp;utm_campaign=xxxxx#data-structures">how</a>.</h3><hr><h2 id="6-counting-sort">6. Counting Sort</h2><p><strong>Counting Sort</strong> is an interesting <strong>sorting technique</strong> primarily because it focuses on the frequency of unique elements between a specific range (something along the lines of hashing).<br>It works by counting the number of elements having distinct key values and then building a sorted array after calculating the position of each unique element in the unsorted sequence.<br>It stands apart from the algorithms listed above because it literally involves zero comparisons between the input data elements!<br></p><h3 id="understanding-counting-sort-algorithm-with-an-example">Understanding Counting Sort algorithm with an example</h3><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://www.crio.do/blog/content/images/2022/01/Counting-sort-algorithm-example-1.png" class="kg-image" alt="10 Best Sorting Algorithms You Must Know About" loading="lazy" width="1920" height="1622" srcset="https://www.crio.do/blog/content/images/size/w600/2022/01/Counting-sort-algorithm-example-1.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/01/Counting-sort-algorithm-example-1.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/01/Counting-sort-algorithm-example-1.png 1600w, https://www.crio.do/blog/content/images/2022/01/Counting-sort-algorithm-example-1.png 1920w" sizes="(min-width: 720px) 720px"><figcaption>Counting sort algorithm explained</figcaption></figure><p>Now go ahead and quickly take a look at its implementation in C++</p><figure class="kg-card kg-code-card"><pre><code class="language-C++">#include&lt;bits/stdc++.h&gt;
using namespace std;

void print(long *vec, long n) {
   for(long i = 1; i&lt;=n; i++)
      cout &lt;&lt; vec[i] &lt;&lt; &quot; &quot;;
   cout &lt;&lt; &quot;\n&quot;;
}

long getMax(long vec[], long n) {
   long max = vec[1];
   for(long i = 2; i&lt;=n; i++) {
      if(vec[i] &gt; max)
         max = vec[i];
   }
   return max;
}
void countSort(long *vec, long n) {
   long output[n+1];
   long max = getMax(vec, n);
   long count[max+1];
   for(long i = 0; i&lt;=max; i++)
      count[i] = 0;
   for(long i = 1; i &lt;=n; i++)
      count[vec[i]]++;
   for(long i = 1; i&lt;=max; i++)
      count[i] += count[i-1];
   for(long i = n; i&gt;=1; i--) {
      output[count[vec[i]]] = vec[i];
      count[vec[i]] -= 1;
   }
   for(long i = 1; i&lt;=n; i++) {
      vec[i] = output[i];
   }
}
int main() {
   long n;
   cout &lt;&lt; &quot;Enter the size of array: &quot;;
   cin &gt;&gt; n;
   long arr[n+1];
   cout &lt;&lt; &quot;Enter elements:&quot; &lt;&lt; endl;
   for(long i = 1; i&lt;=n; i++)
      cin &gt;&gt; arr[i];
   cout &lt;&lt; &quot;Unsorted array: &quot;;
   print(arr, n);
   countSort(arr, n);
   cout &lt;&lt; &quot;Sorted array: &quot;;
   print(arr, n);
}</code></pre><figcaption>Counting Sort Implementation</figcaption></figure><p><br><strong>Time Complexity:</strong></p><ul><li><em>Worst Case:</em> O(n+k), where n is the size of input array and k is the count of unique elements in the array</li></ul><p><strong>Auxiliary Space Complexity:</strong> O(n+k)</p><h3 id="use-cases-5">Use Cases</h3><ul><li>Counting sort is quite efficient when it comes to sorting countable objects (such as bounded integers).</li><li>It is also used when sorting is to be achieved in linear complexity.</li></ul><h3 id="try-it-yourself-5"><u>Try it yourself</u></h3><p>Q. Given an array of n input integers, return the absolute difference between the maximum and minimum elements of the array in linear time complexity.</p><p><strong>Input:</strong></p><ul><li>n -&gt; Size of array (n&gt;1)</li><li>&apos;n&apos; array elements below</li></ul><p><strong>Output: </strong>A single line representing the required difference.</p><p><strong>P.S</strong>: Don&apos;t forget to share your approach with us in the comments below.</p><hr><!--kg-card-begin: markdown--><h3 id="stop-scrolling">Stop scrolling..</h3>
<!--kg-card-end: markdown--><p>You&apos;re done with over 50% of the blog. Want to test your knowledge on how well you&apos;ve understood sorting algorithms so far? Take these quizzes to know where you stand. </p><!--kg-card-begin: html--><a href="https://www.crio.do/learn/v2/magic/sorting-quiz-1/?utm_source=crio-blog&amp;utm_medium=tsa" class="btn">Sorting Algorithms Quiz (Level 1)</a><!--kg-card-end: html--><p></p><!--kg-card-begin: html--><a href="https://www.crio.do/learn/v2/magic/sorting-quiz-2/?utm_source=crio-blog&amp;utm_medium=tsa" class="btn">Sorting Algorithms Quiz (Level 2)</a><!--kg-card-end: html--><hr><h2 id="7-radix-sort">7. Radix Sort</h2><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/12/Radix-Sort.gif" class="kg-image" alt="10 Best Sorting Algorithms You Must Know About" loading="lazy" width="958" height="810"></figure><p>As you saw earlier, <strong>counting sort</strong> stands apart because it&apos;s not a comparison-based <strong>sorting algorithm</strong> like <strong>Merge Sort</strong> or <strong>Bubble Sort</strong>, thereby reducing its <strong>time complexity</strong> to linear time.<br>BUT, <strong>counting sort</strong> fails if the input array ranges from 1 to n^2 in which case its <strong>time complexity</strong> increases to O(n^2).<br>The basic idea behind <strong>radix sorting</strong> is to extend the functionality of <strong>counting sort</strong> to get a better <strong>time-complexity</strong> when input array elements range from 1 till n^2.</p><h3 id="understanding-radix-sort-with-an-example">Understanding Radix Sort with an example</h3><p><strong>Algorithm:</strong></p><p>For each digit i where i varies from the least significant digit to the most significant digit of a number, sort input array using count sort algorithm according to the ith digit. Remember we use count sort because it is a stable sorting algorithm.</p><p><strong>Example:</strong></p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://www.crio.do/blog/content/images/2022/01/Radix-sort-algorithm-example-1.png" class="kg-image" alt="10 Best Sorting Algorithms You Must Know About" loading="lazy" width="1920" height="1236" srcset="https://www.crio.do/blog/content/images/size/w600/2022/01/Radix-sort-algorithm-example-1.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/01/Radix-sort-algorithm-example-1.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/01/Radix-sort-algorithm-example-1.png 1600w, https://www.crio.do/blog/content/images/2022/01/Radix-sort-algorithm-example-1.png 1920w" sizes="(min-width: 720px) 720px"><figcaption>Radix sort algorithm explained</figcaption></figure><p>Thus we observe that radix sort utilizes counting sort as its subroutine throughout its execution. Now take a look at its C++ implementation.</p><figure class="kg-card kg-code-card"><pre><code class="language-C++">#include&lt;bits/stdc++.h&gt;
using namespace std;

long getMax(long vec[], long n){
    long maxval = vec[0];
    for (long i = 1; i &lt; n; i++)
        if (vec[i] &gt; maxval)
            maxval = vec[i];
    return maxval;
}

void Count_Sort(long vec[], long n, long x){
    long res[n];
    long i, count[10] = {0};
    for (i = 0; i &lt; n; i++)
        count[(vec[i] / x) % 10]++;
    for (i = 1; i &lt; 10; i++)
        count[i] += count[i - 1];
    for (i = n - 1; i &gt;= 0; i--) {
        res[count[(vec[i] / x) % 10] - 1] = vec[i];
        count[(vec[i] / x) % 10]--;
    }
    for (i = 0; i &lt; n; i++)
        vec[i] = res[i];
}

void Radix_Sort(long vec[], long n){
    long m = getMax(vec, n);
    for (long x = 1; m / x &gt; 0; x *= 10)
        Count_Sort(vec, n, x);
}

int main(){
    long vec[] = { 53, 89, 150, 36, 633, 233 };
    long n = sizeof(vec) / sizeof(vec[0]);
    Radix_Sort(vec, n);
    for(long i = 0; i &lt; n; i++)
      cout &lt;&lt; vec[i] &lt;&lt; &quot; &quot;;
    return 0;
}</code></pre><figcaption>Radix Sort Implementation</figcaption></figure><p><strong>Time Complexity:</strong> O(d(n+b)), where b represents the base of array element (eg- 10 represents decimal)</p><p><strong>Auxiliary Space Complexity:</strong> O(n+d), where d is the maximum number of digits in an array element.</p><h3 id="use-cases-6">Use Cases</h3><ul><li>Radix sorting finds applications in <a href="https://en.wikipedia.org/wiki/Parallel_computing">parallel computing</a>.</li><li>It is also used in the <a href="http://spencer-carroll.com/the-dc3-algorithm-made-simple/">DC3 algorithm</a> (K&#xE4;rkk&#xE4;inen-Sanders-Burkhardt) while making a suffix array.</li></ul><h3 id="try-it-yourself-6"><u>Try it yourself:</u></h3><p>Q. Given two sorted arrays(arr1[] and arr2[]) of size <strong>M</strong> and <strong>N</strong> of distinct elements. Given a value <strong>Sum</strong>. The problem is to count all pairs from both arrays whose sum is equal to <strong>Sum.</strong></p><p><strong><strong>Note:</strong> The pair has an element from each array.</strong> [Constraint: Use Radix Sort]</p><p><strong>Input:</strong></p><ul><li>n -&gt; Size of array (n&gt;1)</li><li>&apos;n&apos; array elements below</li></ul><p><strong>Output: </strong>A single line representing the required number of pairs</p><p><br><strong>P.S</strong>: Don&apos;t forget to share your approach with us in the comments below.</p><hr><h2 id="8-bucket-sort">8. Bucket Sort</h2><p><strong>Bucket Sort</strong> is a comparison-based <strong>sorting technique</strong> that operates on array elements by dividing them into multiple buckets recursively and then sorting these buckets individually using a separate <strong>sorting algorithm</strong> altogether. Finally, the sorted buckets are re-combined to produce the sorted array.</p><h3 id="understanding-bucket-sort-algorithm-with-pseudocode">Understanding Bucket Sort algorithm with pseudocode</h3><p>We can probe further into the working of <strong>bucket sort</strong> by assuming that we&apos;ve already created an array of multiple &apos;buckets&apos; (lists). Elements are now inserted from the unsorted array into these &quot;buckets&quot; based on their properties. These buckets are finally sorted separately using the <strong>insertion sort algorithm</strong> as explained earlier.</p><p><strong>Pseudocode:</strong></p><pre><code class="language-Pseudocode">Begin
   for i = 0 to size-1
      insert array[i] into the bucket indexed (size * array[i])
   done
   for i = 0 to size-1
      sort bucket[i] using insertion sort
   done
   for i = 0 to size-1
      Combine items of bucket[i] and insert in array in sorted order
   done
End</code></pre><p>Well if you&apos;re still unsure about the bucket sort algorithm, go back and review the pseudocode one more time.</p><p>.</p><p>.</p><p>Done? All right. Now take a quick look at its implementation below.</p><figure class="kg-card kg-code-card"><pre><code class="language-C++">#include&lt;bits/stdc++.h&gt;
#define pb push_back
using namespace std;

void Bucket_Sort(float arr[], int n){
	vector&lt;float&gt; bucket[n];
	for (int i = 0; i &lt; n; i++) {
		int bi = n * arr[i];
		bucket[bi].pb(arr[i]);
	}
	for (int i = 0; i &lt; n; i++)
		sort(bucket[i].begin(), bucket[i].end());
	int pos = 0;
	for (int i = 0; i &lt; n; i++)
		for (int j = 0; j &lt; bucket[i].size(); j++)
			arr[pos++] = bucket[i][j];
}

int main(){
	float arr[]= { 0.474, 0.582, 0.452, 0.6194, 0.553, 0.9414 };
	int n = sizeof(arr) / sizeof(arr[0]);
	Bucket_Sort(arr, n);
	cout &lt;&lt; &quot;Sorted array is \n&quot;;
	for (int i = 0; i &lt; n; i++)
		cout &lt;&lt; arr[i] &lt;&lt; &quot; &quot;;
	return 0;
}</code></pre><figcaption>Bucket Sort Implementation</figcaption></figure><p><strong>Time Complexity:</strong></p><ul><li><em>Worst Case:</em> O(n*n)</li><li><em>Average Case:</em> O(n + k)</li><li><em>Best case:</em> O(n + k)</li></ul><p><strong>Auxiliary Space Complexity:</strong> O(k), worst case</p><h3 id="use-cases-7">Use Cases</h3><ul><li>Bucket sorting is used when input is uniformly distributed over a range.</li><li>It is also used for floating point values.</li></ul><h3 id="try-it-yourself-7"><u>Try it yourself</u></h3><p>Q. You are given two arrays,<strong> A</strong> and <strong>B</strong>, of equal size <strong>N</strong>. The task is to find the minimum value of <strong>A[0] * B[0] + A[1] * B[1] +&#x2026;+ A[N-1] * B[N-1],</strong> where shuffling of elements of arrays <strong>A</strong> and <strong>B</strong> is allowed. [Constraint: Use Bucket Sort]</p><p><strong>Input:</strong></p><ul><li>n -&gt; Size of array (n&gt;1)</li><li>&apos;n&apos; array elements representing the first array</li><li>&apos;n&apos; array elements representing the second array</li></ul><p><strong>Output: </strong>A single line representing the required sum</p><p><br><strong>P.S</strong>: Need help? Drop a comment below.</p><hr><h2 id="9-comb-sort">9. Comb Sort</h2><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/12/Comb-Sort.gif" class="kg-image" alt="10 Best Sorting Algorithms You Must Know About" loading="lazy" width="958" height="810"></figure><p><strong>Comb sort</strong> is quite interesting. In fact, it is an improvement over the <strong>bubble sort algorithm</strong>. If you&apos;ve observed earlier, <strong>bubble sort</strong> compares adjacent elements for every iteration.<br>But for <strong>comb sort</strong>, the items are compared and swapped by a large gap value. The gap value shrinks by a factor of 1.3 for each iteration until the gap value reaches 1, at which point it stops execution.<br>This shrink factor has been empirically calculated to be 1.3 (after testing Comb Sort algorithm on over 2, 00, 000 random arrays) [Source: Wiki] </p><h3 id="understanding-comb-sort-algorithm-with-a-simple-example">Understanding Comb Sort algorithm with a simple example</h3><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://www.crio.do/blog/content/images/2022/01/Comb-sort-algorithm-example-1.png" class="kg-image" alt="10 Best Sorting Algorithms You Must Know About" loading="lazy" width="1920" height="1695" srcset="https://www.crio.do/blog/content/images/size/w600/2022/01/Comb-sort-algorithm-example-1.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/01/Comb-sort-algorithm-example-1.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/01/Comb-sort-algorithm-example-1.png 1600w, https://www.crio.do/blog/content/images/2022/01/Comb-sort-algorithm-example-1.png 1920w" sizes="(min-width: 720px) 720px"><figcaption>Comb sort algorithm explained</figcaption></figure><p>Pretty simple right? Well, let&apos;s have a look at it&apos;s C++ implementation:</p><figure class="kg-card kg-code-card"><pre><code class="language-C++">#include&lt;bits/stdc++.h&gt;
using namespace std;
void Comb_Sort(long *vec, long size) {
   long gap = size;
   bool f = true;
   while(gap != 1 || f == true) {
      gap = (gap)/1.3;
      if(gap&lt;1) gap = 1;
      f = false;
      for(long i = 0; i&lt; size - gap; i++) {
         if(vec[i] &gt; vec[i+gap]) {
            swap(vec[i], vec[i+gap]);
            f = true;
         }
      }
   }
}
int main() {
   long arr[10]={ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
   cout &lt;&lt; &quot;Array before Sorting: &quot;;
   for(long i = 0; i &lt; 10; i++)
      cout &lt;&lt; arr[i] &lt;&lt; &quot; &quot;;
   cout &lt;&lt; endl;
   Comb_Sort(arr, 10);
   cout &lt;&lt; &quot;Array after Sorting: &quot;;
   for(long i = 0; i &lt; 10; i++)
      cout &lt;&lt; arr[i] &lt;&lt; &quot; &quot;;
   cout &lt;&lt; endl;
}</code></pre><figcaption>Comb Sort Implementation</figcaption></figure><p><strong>Time Complexity:</strong></p><ul><li><em>Worst Case:</em> O(n^2)</li><li><em>Average Case:</em> O(n^2/2^p), where p is a number of increment</li><li><em>Best case:</em> O(n*logn)</li></ul><p><strong>Auxiliary Space Complexity:</strong> O(1)</p><h3 id="use-cases-8">Use Cases</h3><ul><li><strong>Comb Sort</strong> eliminates small values at the end of the list by using larger gaps.</li><li>It<strong> </strong>is a significant improvement over Bubble Sort.</li></ul><h3 id="try-it-yourself-8"><u>Try it yourself</u></h3><p>Q. <strong>Given an array, find the most frequent element in it. If there are multiple elements that appear maximum number of times, print any one of them.</strong> [Constraint: Use Comb Sort]</p><p><strong>Input:</strong></p><ul><li>n -&gt; Size of array (n&gt;0)</li><li>&apos;n&apos; array elements below</li></ul><p><strong>Output: </strong>A single line representing the element with maximum frequency.</p><p><strong>P.S</strong>: Did you enjoy this sorting technique? Share your opinions below.</p><hr><h2 id="10-shell-sort">10. Shell Sort</h2><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/12/Shell-Sort.gif" class="kg-image" alt="10 Best Sorting Algorithms You Must Know About" loading="lazy" width="958" height="810"></figure><p><strong>Shell sort algorithm</strong> is an improvement over the <strong>insertion sort algorithm</strong> wherein we resort to diminishing partitions to sort our data.<br>In each pass, we reduce the gap size to half of its previous value for each pass throughout the array. Thus for each iteration, the array elements are compared by the calculated gap value and swapped (if necessary).</p><h3 id="understanding-shell-sort-algorithm-with-pseudocode">Understanding Shell Sort algorithm with pseudocode</h3><pre><code class="language-Pseudocode">Start
   for gap = N / 2, where gap &gt; 0 and gap updates to gap / 2:
      for i= gap to N &#x2013; 1:
         for j = j-gap to 0, decrease by gap value:
            if arr[j+gap] &gt;= arr[j]
               break
            else
               swap arr[j+gap] with arr[j]
         done
      done
   done
End</code></pre><p>The idea of <strong>shell sort</strong> is that it permits the exchange of elements located far from each other. In <strong>Shell Sort</strong>, we make the array N-sorted for a large value of N.<br>We then keep reducing the value of N until it becomes 1. An array is said to be N-sorted if all subarrays of every N&#x2019;th element are sorted.<br>Here, gap size= floor(N/2) for each iteration<br>Finally, take a look at it&apos;s C++ implementation:</p><figure class="kg-card kg-code-card"><pre><code class="language-C++">#include&lt;bits/stdc++.h&gt;
using namespace std;
int Shell_Sort(int vec[], int n){
	for (int gap = n/2; gap &gt; 0; gap /= 2){
		for (int i = gap; i &lt; n; i ++ ){
			int x = vec[i];
			int j;
			for (j=i; j&gt;=gap &amp;&amp; vec[j-gap]&gt;x;j-=gap)
				vec[j] = vec[j - gap];
			vec[j] = x;
		}
	}
	return 0;
}

int main(){
	int vec[] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
	int n = sizeof(vec)/sizeof(vec[0]), i;
	cout &lt;&lt; &quot;Unsorted array: \n&quot;;
	for (int i=0; i&lt;n; i++) cout &lt;&lt; vec[i] &lt;&lt; &quot; &quot;;
	Shell_Sort(vec, n);
	cout &lt;&lt; &quot;\nSorted array: \n&quot;;
	for (int i=0; i&lt;n; i++) cout &lt;&lt; vec[i] &lt;&lt; &quot; &quot;;
	return 0;
}</code></pre><figcaption>Shell Sort Implementation</figcaption></figure><p><strong>Time Complexity:</strong></p><ul><li><em>Worst Case:</em> Depends on gap size</li><li><em>Average Case:</em> Depends on gap size</li><li><em>Best case:</em> O(n*logn)</li></ul><p><strong>Auxiliary Space Complexity:</strong> O(1)</p><h3 id="use-cases-9">Use Cases</h3><ul><li>Insertion sort does not perform well when the close elements are far apart. Shell sort helps reduce the distance between close elements.</li><li>It is also used when recursion exceeds a limit. The <a href="https://en.wikipedia.org/wiki/Bzip2">bzip2 compressor</a> compresses it.</li></ul><h3 id="try-it-yourself-9"><u>Try it yourself</u></h3><p>Q. Given an unsorted array of integers. Write a program to remove duplicates from the unsorted array. [Constraint: Use Shell Sort]</p><p><strong>Input:</strong></p><ul><li>n -&gt; Size of array (n&gt;1)</li><li>&apos;n&apos; array elements below</li></ul><p><strong>Output: </strong>A single line representing the modified array.</p><hr><p>Now that you&apos;ve explored the<strong> Top 10 sorting algorithms</strong>, all that&apos;s left is to answer a few basic questions (just 3 in fact). This will hardly take a minute.</p><h3 id="q1-which-is-the-best-sorting-algorithm">Q1. Which is the best sorting algorithm?</h3><p>If you&apos;ve observed, the <strong>time complexity</strong> of <strong>Quicksort</strong> is O(n logn) in the best and average case scenarios and O(n^2) in the worst case.<br>But since it has the upper hand in the average cases for most inputs, <strong>Quicksort</strong> is generally considered the &#x201C;fastest&#x201D; <strong>sorting algorithm</strong>.<br>At the end of the day though, the best <strong>sorting algorithm</strong> comes down to the nature of your input data (and who you ask).</p><h3 id="q2-what-is-the-easiest-sorting-algorithm">Q2. What is the easiest sorting algorithm?</h3><p><strong>Bubble sort</strong> is widely recognized as the simplest <strong>sorting algorithm</strong> out there. Its basic idea is to scan through an entire array and compare adjacent elements and swap them (if necessary) until the list is sorted. Pretty simple right?</p><h3 id="q3-which-sorting-algorithm-would-you-prefer-for-nearly-sorted-lists">Q3. Which sorting algorithm would you prefer for nearly sorted lists?</h3><p>When it comes to sorting nearly sorted data, <strong>insertion sort</strong> is the clear winner particularly because it&apos;s <strong>time complexity</strong> reduces to O(n) from a whopping O(n^2) on such a sample.</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/insertion-sort/?utm_source=blog-int"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Master Insertion Sort Before Your Next Big Interview</div><div class="kg-bookmark-description">Learn the details of insertion sort and how you can use it effectively to sort your dataset</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="10 Best Sorting Algorithms You Must Know About"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Harshita Bansal</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/08/Insertion-sort.png" alt="10 Best Sorting Algorithms You Must Know About"></div></a></figure><p>On the other hand, merge sort or quick sort algorithms do not adapt well to nearly sorted data.</p><blockquote>Well, that&apos;s about it. At the end of the day, it&apos;s up to you to decide which sorting technique suits you the best. And yes, don&apos;t forget to try out the practice problems served alongside with each sorting technique.</blockquote><!--kg-card-begin: markdown--><h3 id="how-comfortable-are-you-with-sorting-now">How comfortable are you with sorting now?</h3>
<!--kg-card-end: markdown--><p>Before you go for your next interview, be sure to know the answers to these commonly asked Sorting Algorithms questions. If you read this blog thoroughly, you&apos;re all set to get a perfect score. Ready to take the quiz?</p><!--kg-card-begin: html--><a href="https://www.crio.do/magic/sorting-quiz-2/?utm_source=crio-blog&amp;utm_medium=tsa" class="btn">Start Quiz</a><!--kg-card-end: html--><hr><h3 id="go-beyond-video-based-certification-courses-and-online-bootcamps-build-the-confidence-you-need-to-take-on-data-structures-and-algorithm-questions-in-your-next-big-interview-and-land-your-dream-job-as-a-backend-developer-or-full-stack-developerguaranteed-find-out-how">Go beyond video-based certification courses and online bootcamps. Build the confidence you need to take on Data Structures and Algorithm questions in your next big interview and land your dream job as a Backend Developer or Full Stack Developer - Guaranteed! <a href="https://www.crio.do/software-development-fellowship-program/?utm_source=crio-blog&amp;utm_medium=tsa">Find out how</a>.</h3><hr><h3 id="additional-resources">Additional resources</h3><p>Don&apos;t miss these free learning resources that are an absolute essential for all developers: </p><ol><li>100+ Essential Linux commands You Must Know. <a href="https://bit.ly/3FHmONt">Download PDF &gt;&gt;</a></li><li>Useful VScode shortcuts To Become A Ninja Programmer. <a href="https://bit.ly/3wXRLth">Download PDF &gt;&gt;</a></li><li>Git commands Cheat Sheet. <a href="https://bit.ly/3CrEN8k">Download Cheat Sheet &gt;&gt;</a></li><li>20+ Interesting Tech Projects with Step-By-Step Instructions. <a href="https://bit.ly/3DrxbUQ">Download Projects &gt;&gt;</a></li></ol><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><hr><p>Found this article interesting? Show your love by upvoting this article.<br>We would also love to know the <strong>sorting technique</strong> that got you excited the most - let us know in the comments below.<br>Also, if you enjoyed reading this article, don&apos;t forget to share it with your friends!</p><p></p><p></p><p></p><p></p><p></p><p></p>]]></content:encoded></item><item><title><![CDATA[Crio DevSprint: Applied Data Structures and Algorithms]]></title><description><![CDATA[Comprehensive study plan to sharpen your DS/Algo skills covering Array, Strings, Linked List, Hash, Heap, Stack, Queue, Tree, Graph, Dynamic Programming, Segment Trees, Tries etc. ]]></description><link>https://www.crio.do/blog/crio-devsprint-applied-data-structures-and-algorithms-2024/</link><guid isPermaLink="false">66c783bc134c11095afa92c1</guid><category><![CDATA[Data Structures and Algorithms]]></category><dc:creator><![CDATA[Ajay Ravindra]]></dc:creator><pubDate>Tue, 09 Jul 2024 07:45:00 GMT</pubDate><media:content url="https://www.crio.do/blog/content/images/2020/07/blog_default.png" medium="image"/><content:encoded><![CDATA[<blockquote>Note: we are currently not accepting applications for our Applied Data Structures and Algorithms track. Feel free to browse the details of the track in this post and email us at <a>ping@criodo.com</a> to get notified of upcoming batches.</blockquote><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><img src="https://www.crio.do/blog/content/images/2020/07/blog_default.png" alt="Crio DevSprint: Applied Data Structures and Algorithms"><p><strong>Want to switch jobs, but insufficient Data Structures and Algorithms prep is getting in the way?</strong></p><p>Looking for a comprehensive study plan to sharpen your DS/Algo skills? Don&apos;t feel confident about approaching unseen problems in coding interviews?</p><p><strong>The Crio DevSprint Applied Data Structures and Algorithms program is the right fit for you.</strong> We have the most rigorous learning plan packed into an efficient 8-week schedule (details).</p><h2 id="topics-you-will-master">Topics you will master</h2><p>During the course of the 8-week schedule, you will master concepts and frequently occurring problem patterns in the following topics (details):</p><ul><li><strong>Foundational topics:</strong> Arrays and Strings, Linked Lists, Stacks, Hashes, Heaps, Recursion, Backtracking, Trees and Graphs, and more.</li><li><strong>Advanced topics:</strong> Dynamic Programming, Greedy Algorithms, Segment Trees, Tries, Spanning Tree, and more.</li></ul><h2 id="what-you-will-get">What you will get</h2><h3 id="1-crio-s-effective-problem-solving-methodology">1. Crio&#x2019;s effective problem-solving methodology</h3><ul><li>Don&apos;t waste your time solving hundreds of problems. When it comes to preparing for PS/DSA interviews, quality beats quantity. Our effective approach significantly improves your chances of solving unseen problems in an interview setting..</li></ul><h3 id="2-targeted-practice-confidence">2. Targeted practice <em>=&gt; Confidence</em></h3><ul><li>You will solve <strong>150+ problems</strong> using our recommended approach.</li></ul><h3 id="3-curated-concept-wise-problem-sets">3. Curated concept-wise problem sets</h3><ul><li>Explore and analyse <em>key problem patterns</em> with a high hit-rate in coding interviews.</li></ul><h3 id="4-a-clear-weekly-plan-disciplined-orchestration">4. A clear weekly plan + disciplined orchestration</h3><ul><li>We will hold you accountable to your weekly targets. Get frequent reminders about what is due and when.</li></ul><h3 id="5-16-timed-mock-assessments">5. 16 timed mock assessments</h3><ul><li>Two mock assessments <em>every week</em>.</li><li><em>Measure your progress </em>through these mocks that mimic screening tests.</li></ul><h3 id="6-live-mentoring-sessions-daily-mentoring-hours">6. Live mentoring sessions + daily mentoring hours</h3><ul><li><em>Live sessions</em> to discuss concepts in detail and address your questions.</li><li>Daily mentoring hours with TAs who are joining top-tech companies like Google and Amazon.</li><li>Watch weekly <em>live mock interview sessions</em> and get familiar with an interview setting.</li></ul><h3 id="7-meaningful-help-and-interventions">7. Meaningful help and interventions</h3><ul><li>Every problem ships with multiple <em>hints</em> to unblock yourself when stuck.</li><li>Hints give you just enough help to <em>move forward without giving you the whole solution</em> - enabling you to try to solve the problem on your own.</li><li><em>Solution editorials </em>are also included to cover complexity analysis and alternative approaches.</li></ul><h3 id="8-a-vibrant-community-of-driven-peers">8. A vibrant community of driven peers</h3><ul><li>Interact with peers and work with them towards a <em>common goal</em>. Help each other and enhance your knowledge.</li></ul><h3 id="9-premium-mock-interviews">9. (Premium) Mock interviews</h3><ul><li>Purchase mock interviews conducted by developers in Google, Amazon, Microsoft and other top-tech companies.</li><li>Get detailed feedback on your strengths and areas of improvement.</li><li>Targeted action items to help improve your interview performance.</li></ul><p>Get the <em><strong><a href="https://crio.do/?utm_source=crio-blog&amp;utm_medium=cdadsad">Crio Advantage</a></strong></em> and achieve predictable success in your next coding interview!</p><blockquote>Note: we are currently not accepting applications for our Applied Data Structures and Algorithms track. Feel free to browse the details of the track in this post and email us at <a>ping@criodo.com</a> to get notified of upcoming batches.</blockquote><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure>]]></content:encoded></item><item><title><![CDATA[The Complete Quick Sort Guide]]></title><description><![CDATA[Learn the fundamentals of Quick Sort with an example. Sharpen your understanding with fun quizzes and activities]]></description><link>https://www.crio.do/blog/quick-sort-2/</link><guid isPermaLink="false">66c783bc134c11095afa930a</guid><category><![CDATA[Data Structures and Algorithms]]></category><dc:creator><![CDATA[Abheetha Pradhan]]></dc:creator><pubDate>Thu, 09 May 2024 03:57:00 GMT</pubDate><media:content url="https://www.crio.do/blog/content/images/2022/02/The-Complete-Quick-Sort-Guide.png" medium="image"/><content:encoded><![CDATA[<h2 id="introduction-to-sorting">Introduction to Sorting</h2><img src="https://www.crio.do/blog/content/images/2022/02/The-Complete-Quick-Sort-Guide.png" alt="The Complete Quick Sort Guide"><p>Sorting is one of the most important problems that is studied in computer science. It is necessary for any application to run smoothly. </p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/top-10-sorting-algorithms/?utm_source=blog-int"><div class="kg-bookmark-content"><div class="kg-bookmark-title">10 Best Sorting Algorithms - Explained with Simple Examples</div><div class="kg-bookmark-description">Find out which is the best sorting algorithm. Understand how to use the different types of sorting algorithms with simple examples.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="The Complete Quick Sort Guide"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Sandipan Das</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/04/Sorting-Algorithms.png" alt="The Complete Quick Sort Guide"></div></a></figure><p>Say you just started a clothing website, and you need to add a filter that sorts the clothes according to their price. </p><p>You definitely need code that will sort these clothes in a particular order. <br>There are some inbuilt sorting functions in most programming languages, that will easily help you do this. </p><p>But in the 1950s, computer scientists had just begun to invent sorting algorithms. <br>Hoare invented Quick Sort in 1961. Before you start reading about Quick Sort, think about how you would create a sorting algorithm. Doing this will make you appreciate how well thought out Quick Sort is. </p><p>Sorting particular items would mean arranging them in a particular order. For the items to be orderable, each item must be comparable with every other item. So the basic operation you&#x2019;d need to perform to sort a list of items would be comparisons. Now the question is, how would you perform these comparisons. Comparing each and every item in a list with every other item is tedious. </p><p>For example, you can sort the letters of a word in alphabetical order. But you can&#x2019;t sort a list of different colors, unless some sorting criteria is specified. <br>But a list can have identical elements, it can be empty, it can have just one element, or all the elements can be identical. Most sorting algorithms take care of all of these cases.</p><p>Quick Sort offers a solution of its own for sorting a list of items in an efficient way.</p><p>In this blog, you will learn two variants of Quick Sort</p><ul><li>Quick Sort with the first element in the array as the pivot</li><li>Quick Sort with a random pivot</li></ul><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><h2 id="what-is-quick-sort">What is Quick Sort</h2><p>Quick Sort is a <strong>Divide and Conquer algorithm</strong>. </p><p>Divide and conquer is a problem-solving technique where a problem is divided recursively into smaller instances. The solutions of these instances are then combined, which gives the solution for the original problem itself.</p><p>Quick Sort will rearrange the elements in a given array that needs to be sorted, such that it achieves a partition. An element &#x2018;s&#x2019; is placed in this position of partition in the array, such that all the elements to the left of s are smaller than s and all the elements to the right of s are larger than s. </p><p>The element &#x2018;s&#x2019; will be in its final position in the array once a partition has been found. Quick Sort will now proceed to recursively sort the left and right subarrays.</p><hr><p><strong>Check out this other Divide and Conquer algorithm in detail:</strong></p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/merge-sort-algorithm/?utm_source=blog-int"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Everything You Need To Know About Merge Sort</div><div class="kg-bookmark-description">Learn the fundamentals of Merge Sort with an example. Sharpen your understanding with fun quizzes and activities.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="The Complete Quick Sort Guide"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Abheetha Pradhan</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/09/Merge-sort.png" alt="The Complete Quick Sort Guide"></div></a></figure><hr><h2 id="algorithm-design-for-quick-sort-with-the-first-element-as-the-pivot">Algorithm Design for Quick Sort with the first element as the pivot</h2><h3 id="pseudocode">Pseudocode</h3><!--kg-card-begin: html--><pre>
<code>
QuickSort(A[l..r])
//Input:A subarray A[l..r] of A[0..n-1], where l and r are left most and 
//right most indices of the subarray of A
//Output: Subarray A[l..r] sorted in non decreasing order

If l &lt; r

	s = Partition(A[l..r]) 
    
   	 //s is split position returned by partition subroutine
	//Apply Quick Sort to array elements to the left of the partition s
    QuickSort(A,l,s-1)
    
	//Apply Quick Sort to array elements to the right of the partition s
    QuickSort(A,s+1,r) 

</code>
</pre><!--kg-card-end: html--><p>You can see that there are two subroutines, Partition and Quick Sort. First, you need to find a pivot(s). </p><h2 id="what-is-pivot-in-sorting">What is Pivot in sorting</h2><p>It is an element that needs to be placed at a position at which the array can be partitioned such that all elements to the left of the pivot are at most equal to the pivot, and all elements to the right of the pivot are greater than the pivot.</p><p><strong>Partition</strong> will find a position or index &#x2018;s&#x2019; where the pivot can be placed and returns this. The array now has now been split, based on this partition. The split index is then passed to QuickSort, a recursive function, which will sort the left subarray first, and then proceed to sort the right subarray, using the same idea. </p><p>Understand this better with the illustration below:</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Pivot-in-quick-sort.png" class="kg-image" alt="The Complete Quick Sort Guide" loading="lazy" width="1920" height="1235" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Pivot-in-quick-sort.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Pivot-in-quick-sort.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/Pivot-in-quick-sort.png 1600w, https://www.crio.do/blog/content/images/2022/02/Pivot-in-quick-sort.png 1920w" sizes="(min-width: 720px) 720px"></figure><p>In this algorithm, you will take the first element as the pivot, and use Partition to find a split position for it. But wait, what about sorting? Partition implements this as well. Let&apos;s look at how Partition works now.</p><!--kg-card-begin: html--><pre>
<code>
Partition(A[l..r])
//Partitions a subarray by using its first element as pivot.
//Input: A subarray A[l..r] of A[0..n-1] defined by its left and right
//indices l and r, l &lt; r
//Output: A partition of A[l..r], with the split position returned as the //function&#x2019;s value

//Assign the first element as pivot
p = A [ l ]
i = l; j = r + 1
repeat
//Traverse  left to right with i , until you find an element greater than or //equal to p
repeat i = i + 1 until A[i] &gt;= p
//Traverse right to left with j , until you find an element lesser than or //equal to p
repeat j = j - 1 until A[j] <= p swap(a[ i ], a[ j ]) repeat the above steps until crosses>= j

swap(A[ i ],  A[ j ] ) //Undo the last swap when i &gt;  j
swap(A[ l ],  A[ j ] )
return j
</=></code>
</pre><!--kg-card-end: html--><p><strong>i: </strong> Starts from the leftmost index of the array. Scans left to right, comparing each element to pivot. Skips over elements that are lesser than the pivot. So, keep incrementing i, until you find a value greater than or equal to the pivot. </p><p><strong>j: </strong>Starts from the rightmost index of the array. Scans right to left, comparing each element to the pivot. Skips over elements that are greater than the pivot. So keep decrementing j, until you find a value lesser than or equal to the pivot. </p><p>Now think about what has been accomplished, if you can&apos;t increment i anymore, and decrement j anymore. They&#x2019;ve halted. Where have they halted? </p><p>There are three scenarios that might occur:</p><ul><li>i has not crossed j, &#xA0;i &lt; j</li><li>i has crossed j, &#xA0;i &gt; j</li><li>i and j are at the same position, &#xA0; i = j</li></ul><h3 id="case-1-i-j">Case 1: i &lt; j</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/quick-sorting-case-1.png" class="kg-image" alt="The Complete Quick Sort Guide" loading="lazy" width="1920" height="860" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/quick-sorting-case-1.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/quick-sorting-case-1.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/quick-sorting-case-1.png 1600w, https://www.crio.do/blog/content/images/2022/02/quick-sorting-case-1.png 1920w" sizes="(min-width: 720px) 720px"></figure><p>If i &lt; j, and they&#x2019;ve halted, it must mean that i has found an element that must be placed to the right of the pivot, and j has found an element that must be placed to the left of the pivot.</p><p>So swap them and resume the scans. Keep in mind that you have not found the position where you need to place the pivot yet. </p><h3 id="case-2-i-j">Case 2: i &gt; j</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/quick-sorting-case-2.png" class="kg-image" alt="The Complete Quick Sort Guide" loading="lazy" width="1920" height="860" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/quick-sorting-case-2.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/quick-sorting-case-2.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/quick-sorting-case-2.png 1600w, https://www.crio.do/blog/content/images/2022/02/quick-sorting-case-2.png 1920w" sizes="(min-width: 720px) 720px"></figure><p>In this case, you must pay attention to what value j has. In the last swap, you would have swapped two elements, the element at j, will be greater than the one at i.</p><p>What you must do now is undo this swap. Brainstorm why you need to do this.<br>If you don&#x2019;t undo this swap, an element greater than the pivot will lie to the left of the pivot, and an element lesser than the pivot to its right. <br><br>Once you undo this swap, you will have an element at j that is smaller than the pivot. Now swap A [ l ](which is the pivot) and A [ j ].</p><h3 id="case-3-i-j">Case 3: i = j</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/quick-sorting-case-3.png" class="kg-image" alt="The Complete Quick Sort Guide" loading="lazy" width="1920" height="706" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/quick-sorting-case-3.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/quick-sorting-case-3.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/quick-sorting-case-3.png 1600w, https://www.crio.do/blog/content/images/2022/02/quick-sorting-case-3.png 1920w" sizes="(min-width: 720px) 720px"></figure><p>Finally, if the scanning indices have stopped pointing to the same indices, the value they are pointing to must be equal to &#x2018;s&#x2019;, the index of partition. The pivot is placed here.</p><p>Therefore, the array is partitioned with split position i = j = s .</p><p>In the next section, you will visualize Quick Sort with an example, and learn about how Quick Sort uses recursion.</p><h2 id="visualizing-quick-sort-with-an-example">Visualizing Quick Sort with an example</h2><p>Using the algorithm you just learned for Partition, trace Partition for an array = [5, 3, 1, 9, 8]</p><p>Your trace of the array should look like the figure below. The highlighted elements are the pivots.</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/visualize-quick-sort-with-example.png" class="kg-image" alt="The Complete Quick Sort Guide" loading="lazy" width="1920" height="2581" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/visualize-quick-sort-with-example.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/visualize-quick-sort-with-example.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/visualize-quick-sort-with-example.png 1600w, https://www.crio.do/blog/content/images/2022/02/visualize-quick-sort-with-example.png 1920w" sizes="(min-width: 720px) 720px"></figure><p>Here is a link to help you visualize Quick Sort</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://visualgo.net/en/sorting?slide=1"><div class="kg-bookmark-content"><div class="kg-bookmark-title">VisuAlgo - Sorting (Bubble, Selection, Insertion, Merge, Quick, Counting, Radix)</div><div class="kg-bookmark-description">Sorting is a very classic problem of reordering items (that can be compared, e.g. integers, floating-point numbers, strings, etc) of an array (or a list) in a certain order (increasing, non-decreasing, decreasing, non-increasing, lexicographical, etc).There are many different sorting algorithms, eac&#x2026;</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://visualgo.net/img/favicon.png" alt="The Complete Quick Sort Guide"><span class="kg-bookmark-author">Sorting (Bubble, Selection, Insertion, Merge, Quick, Counting, Radix)</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://visualgo.net/img/png/sorting.png" alt="The Complete Quick Sort Guide"></div></a></figure><p>(select Quick Sort at the top)</p><h3 id="tree-of-recursive-calls">Tree of recursive calls</h3><p>Quick Sort will first recursively be called on the left half of the tree, then it will work on the right half.</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Tree-of-recursive-calls.png" class="kg-image" alt="The Complete Quick Sort Guide" loading="lazy" width="1920" height="1204" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Tree-of-recursive-calls.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Tree-of-recursive-calls.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/Tree-of-recursive-calls.png 1600w, https://www.crio.do/blog/content/images/2022/02/Tree-of-recursive-calls.png 1920w" sizes="(min-width: 720px) 720px"></figure><p>Here you can see that all the nodes in the last level do not satisfy the condition &#xA0;</p><p>l&lt;r . So, no action is performed.</p><h2 id="implementation-of-quick-sort-in-python">Implementation of Quick Sort in Python</h2><!--kg-card-begin: html--><pre>
<code class="language-Python">
# The main function that implements QuickSort
def quicksort(array, l, r):
if (l &lt; r):
# s is partitioning index
#pivot will be placed in array[s]
s = partition(array,l , r)
# Sort elements before partition
# and after partition
quicksort(array,l, s - 1)
quicksort(array, s + 1, r)

#Partition function that sorts subarrays and returns partitioning index
def partition(array, l, r):
# Initializing pivot&apos;s index to start
i = l
pivot = array[l]
j = r+1
while(i<j): 1 while true: i="i" + if(i>=r or array[i]&gt;=pivot):
break
while True:
j = j - 1
if(j<=l or array[j]<="pivot):" break array[i], array[j]="array[j]," array[i] #swap elements at i and j #undo last swap when> j
array[l], array[j] = array[j], array[l]  #swap pivot and element at j
    
return j #return partition index
    
if __name__ == &quot;__main__&quot;:
array = [9,8,7,6,5]
quicksort(array, 0, len(array) - 1)
print(f&apos;Sorted array: {array}&apos;)
    </=l></j):></code>
    </pre><!--kg-card-end: html--><p>Output: Sorted array: [5, 6, 7, 8, 9]</p><h2 id="implementation-of-quick-sort-using-random-pivot">Implementation of Quick Sort using random pivot</h2><p>Randomized Quick Sort will make use of a random pivot that is selected randomly from the array, instead of choosing the first element as the pivot. This helps to avoid the worst case scenario of Quick Sort.</p><p>In this code, you will randomly select a pivot, and you will swap it with the first element. </p><!--kg-card-begin: html--><pre>
<code class="language-Python">
import random
def randomized_partition(array, l, r):
i = l
pivot = random.randrange(l,r)
# Swap positions of randomly chosen pivot and the first element in the array
array[l], array[pivot] = array[pivot], array[l]

j = r+1
while(i<j): 1 while true: i="i" + if(i>=r or array[i]&gt;=array[l]):
break

while True:
j = j - 1
if(j<=l or array[j]<="array[l]):" break array[i], array[j]="array[j]," array[i] array[l], array[l] return j def randomized_quicksort(array, l, r): if (l < s="randomized_partition(array,l" , r) randomized_quicksort(array,l, - 1) + 1, __name__="=" "__main__": array="[9,8,7,6,5]" 0, len(array) print(f'sorted array: {array}') code>
</=l></j):></code></pre><!--kg-card-end: html--><p>Output:</p><p>Sorted array: [5,6,7,8,9]</p><h3 id="test-your-understanding">Test your understanding</h3><p>Q1. How does the array [5,2,4,9,1,9] look after the first partition?</p><p>Q2. Sorting in Quick Sort occurs within the same array</p><p>		A.True</p><p>		B. False</p><p>Q3. How do you make sure scan indices i and j don&apos;t go out of bound?</p><p>(Hint: Compare Quick Sort algorithm and Quick Sort Python code)</p><p>Q4. Why do we stop scanning when we find an element equal to the pivot?</p><h2 id="time-complexity-analysis">Time Complexity Analysis</h2><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/time-complexity-analysis.png" class="kg-image" alt="The Complete Quick Sort Guide" loading="lazy" width="1920" height="1154" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/time-complexity-analysis.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/time-complexity-analysis.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/time-complexity-analysis.png 1600w, https://www.crio.do/blog/content/images/2022/02/time-complexity-analysis.png 1920w" sizes="(min-width: 720px) 720px"></figure><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/time-complexity-explained/?utm_source=blog-int"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Time Complexity Simplified with Easy Examples</div><div class="kg-bookmark-description">Find out what is time complexity. Understand how to analyze time complexities with simple examples.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="The Complete Quick Sort Guide"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Sandipan Das</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/08/time-complexity-of-sorting-algorithms.png" alt="The Complete Quick Sort Guide"></div></a></figure><h3 id="best-case">Best case</h3><p>Quick Sort makes n + 1 key comparisons if scanning indices cross over. If not, then n comparisons are made. If all partitions occur at the middle of all subarrays, you have the best case scenario.</p><p>Cbest(n) = 2Cbest(n/2) + n for n &gt; 1 , Cbest(1) = 0</p><p>C = number of comparisons made.</p><p>By applying masters theorem,</p><p>Cbest(n) = nlogn</p><h3 id="worst-case">Worst Case</h3><p>The worst case scenario will occur when the array is already sorted. It could be sorted in increasing or decreasing order. All the splits, in this case, will occur at the extremes of the array, and at least one of the two subarrays will be empty.</p><p>It also occurs when all elements are the same.</p><p>Say you have an array that is sorted in increasing order as the input. The scan i will have to scan and compare elements with the pivot all the way till the end of the array. </p><p>First, it will make n + 1 comparisons. It will exchange the pivot element with itself. Now it will run the scan for A[1..n-1]. It will make n comparisons. Then it will scan for A[2..n-1]. It will make n - 1 comparisons, and so on. </p><p>Cworst(n) = (n+1) + n + &#x2026;&#x2026;.. + 3 = (n+1)(n+2)/2</p><p>Which belongs to O(n2)</p><h2 id="time-complexity-comparison-of-quick-sort-and-randomized-quick-sort">Time complexity comparison of Quick Sort and randomized Quick Sort</h2><p>You just learned that the worst case time complexity of Quick Sort is O(n2). Randomized Quick Sort improves the performance. </p><p>The worst case time complexity is still O(n2), but the chances of it occurring are decreased. </p><p>Here you will pass a sorted array to functions quicksort, and randomized_quicksort, and see which one has a better running time. </p><!--kg-card-begin: html--><pre>
<code class="language-Python">
import time
from random import randint
arr1 = [randint(0,1000) for i in range(1000)]
times=[]
times_worstcase = []
randomized_worstcase = []

for x in range(0,1000,10):
start_time = time.time()
arr2 = (arr1[:x])
quicksort(arr2,0, len(arr2)-1)
elapsed_time = time.time() - start_time
times.append(elapsed_time)
#store the sorted array in arr1, so that this imitates worst case scenario for Quick Sort
arr1 = arr2

for x in range(0,1000,10):
start_time = time.time()
arr2 = (arr1[:x])
quicksort(arr2,0, len(arr2)-1)
elapsed_time = time.time() - start_time
times_worstcase.append(elapsed_time)
arr1 = arr2
for x in range(0,1000,10):
arr2 = (arr1[:x])
start_time = time.time()
randomized_quicksort(arr2,0, len(arr2)-1)
elapsed_time = time.time() - start_time
randomized_worstcase.append(elapsed_time)
x=[i for i in range(0,1000,10)]

import matplotlib.pyplot as plt
%matplotlib inline
plt.xlabel(&quot;No. of elements&quot;)
plt.ylabel(&quot;Time required&quot;)
plt.plot(x,times_worstcase,&apos;r&apos;)
plt.plot(x,randomized_worstcase,&apos;b&apos;)
</code>
</pre><!--kg-card-end: html--><h3 id="output">Output</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/quick-sort-output.png" class="kg-image" alt="The Complete Quick Sort Guide" loading="lazy" width="2000" height="1556" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/quick-sort-output.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/quick-sort-output.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/quick-sort-output.png 1600w, https://www.crio.do/blog/content/images/2022/02/quick-sort-output.png 2006w" sizes="(min-width: 720px) 720px"></figure><p>Observe that the running time plot for Quick Sort is leaning towards n2, while randomized_quicksort appears to have nlogn. </p><p>So even though a worst case input was passed to randomized_quicksort, it avoided the worst case by selecting a random pivot instead of the first element itself as the pivot.</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/time-complexity-explained/?utm_source=blog-int"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Time Complexity Simplified with Easy Examples</div><div class="kg-bookmark-description">Find out what is time complexity. Understand how to analyze time complexities with simple examples.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="The Complete Quick Sort Guide"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Sandipan Das</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/08/time-complexity-of-sorting-algorithms.png" alt="The Complete Quick Sort Guide"></div></a></figure><h2 id="further-analysis-of-quick-sort">Further Analysis of Quick Sort</h2><p>The criteria for analyzing any sorting algorithm are the following:</p><h3 id="time-complexity"><a href="https://www.crio.do/blog/time-complexity-explained/?utm_source=blog-int">Time complexity</a></h3><p>The running time of Quick Sort heavily depends on the choice of the pivot element.</p><p>If worst case scenario does not occur in Quick Sort, its performance is comparable with merge sort. Quick Sort is one of the quickest sorting algorithms. Selection sort is the slowest.</p><p>Best case : O(nlogn)</p><p>Worst case: O(n2)</p><p>Average case: O(nlogn)</p><h3 id="space-complexity">Space Complexity</h3><p>Quick sort is an in-place sorting algorithm. It has a space complexity of O(1)</p><p>An in-place algorithm is a sorting algorithm in which the sorted items occupy the same storage as the original ones.</p><p>However, the worst case space complexity is O(logn).</p><h3 id="stability">Stability</h3><p>Quick Sort is not a stable algorithm. An algorithm is said to be stable when it keeps elements with equal values in the same relative order in the output as they were originally, in the input. </p><p>Quick Sort works well on large data sets. Since it is in-place, it doesn&apos;t require additional memory.</p><h2 id="applications-of-quick-sort">Applications of Quick Sort</h2><ul><li>Most commercial applications use Quick Sort to sort data. Data that is a mixture of different items can be assigned priorities and sorted. Miscellaneous data, such as student details, employee details, social media account profile sorting, sorting for e-commerce websites, etc.,<br></li><li>Since Quick Sort works in-place, it is cache friendly<br></li><li>It is used in Operations Research and Event Driven Simulation <br></li><li><strong>Amongst all the sorting algorithms</strong> which have an efficiency of nlogn, Quick Sort works <strong>best</strong> for sorting randomly ordered arrays.<br></li><li>Java&#x2019;s inbuilt Arrays.sort method uses dual pivot Quick Sort algorithm.</li></ul><h3 id="test-your-understanding-1">Test Your Understanding</h3><p>Q4. Strictly decreasing arrays are</p><p>		A. Worst-case input</p><p>		B. Best-case input</p><p>		C. Neither</p><p>Q5. Find out the worst case space complexity of Quick Sort. Why is this the case?</p><p>Q6. Which scenario is the best case for Quick Sort?</p><p>		A.The elements are in ascending order</p><p>		B.The pivot is the smallest element all of the time.</p><p>		C.The elements are in random order</p><p>		D.The elements are in alternating small/large order.</p><p>Q7. Quick Sort is the fastest sorting algorithm</p><p>		A. True</p><p>		B. False</p><h2 id="try-it-yourself">Try it yourself</h2><ol><li>Apply Quick Sort to sort the list L, E, A, R, N, B, Y, D, O, I, N, G in alphabetical order.</li><li>Do a comparative study of Merge Sort and Quick Sort</li><li>Write Quick Sort code with fewer swaps</li></ol><h2 id="conclusion">Conclusion</h2><p>Quick Sort is a heavily researched sorting algorithm as it can be improved in several ways based on how the pivot is chosen, and how the array is partitioned. It performs well on large data sets, and since it works in-place, it is sometimes a better alternative than merge sort. For a large data set of randomly organized numbers, Quick Sort does have a very low running time compared to other sorting algorithms like bubble sort and insertion sort. &#xA0;So yes! Quick Sort is pretty quick in sorting! </p><h2 id="further-reading">Further reading</h2><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/top-10-sorting-algorithms/?utm_source=blog-int"><div class="kg-bookmark-content"><div class="kg-bookmark-title">10 Best Sorting Algorithms - Explained with Simple Examples</div><div class="kg-bookmark-description">Find out which is the best sorting algorithm. Understand how to use the different types of sorting algorithms with simple examples.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="The Complete Quick Sort Guide"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Sandipan Das</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/04/Sorting-Algorithms.png" alt="The Complete Quick Sort Guide"></div></a></figure><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/merge-sort-algorithm/?utm_source=blog-int"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Everything You Need To Know About Merge Sort</div><div class="kg-bookmark-description">Learn the fundamentals of Merge Sort with an example. Sharpen your understanding with fun quizzes and activities.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="The Complete Quick Sort Guide"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Abheetha Pradhan</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/09/Merge-sort.png" alt="The Complete Quick Sort Guide"></div></a></figure><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/time-complexity-explained/?utm_source=blog-int"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Time Complexity Simplified with Easy Examples</div><div class="kg-bookmark-description">Find out what is time complexity. Understand how to analyze time complexities with simple examples.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="The Complete Quick Sort Guide"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Sandipan Das</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/08/time-complexity-of-sorting-algorithms.png" alt="The Complete Quick Sort Guide"></div></a></figure><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/insertion-sort/?utm_source=blog-int"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Master Insertion Sort Before Your Next Big Interview</div><div class="kg-bookmark-description">Learn the details of insertion sort and how you can use it effectively to sort your dataset</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="The Complete Quick Sort Guide"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Harshita Bansal</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/08/Insertion-sort.png" alt="The Complete Quick Sort Guide"></div></a></figure><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure>]]></content:encoded></item><item><title><![CDATA[Top 10 Data Structures Interview Questions (2023)]]></title><description><![CDATA[Coding interviews are comprised mainly of Data Structures and Algorithms. Here are the most commonly asked data structures interview questions and answers for freshers. ]]></description><link>https://www.crio.do/blog/data-structures-interview-questions-2/</link><guid isPermaLink="false">66c783bc134c11095afa9327</guid><category><![CDATA[Data Structures and Algorithms]]></category><dc:creator><![CDATA[Abheetha Pradhan]]></dc:creator><pubDate>Fri, 14 Oct 2022 14:15:00 GMT</pubDate><media:content url="https://www.crio.do/blog/content/images/2022/03/Data-Structures-Interview-Questions.png" medium="image"/><content:encoded><![CDATA[<figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><img src="https://www.crio.do/blog/content/images/2022/03/Data-Structures-Interview-Questions.png" alt="Top 10 Data Structures Interview Questions (2023)"><p>Why do you need knowledge of data structures and algorithms?</p><p><a href="https://www.crio.do/blog/tag/data-structures-and-algorithms/?utm_source=criodo-blog">Data structures and Algorithms</a> are techniques used to write efficient code for a given problem, much like how you need music theory to master an instrument. <strong>To be a good programmer you need to learn to use the right data structure and algorithm for a given problem. </strong></p><p>Say, you need to travel to a particular spot in your city. You take a car to travel to the spot but later discover that taking the metro would have been faster and cheaper. Similarly, insufficient knowledge in DSA can lead you to write inefficient code. </p><p>In interviews, an interviewer will test you on the basis of how quickly you come up with the solution, how efficient your code is, and they can go on to ask you in-depth questions about the data structure or algorithm you&#x2019;ve used to solve the problem. </p><p>The popular opinion for mastering Data Structures and Algorithms is to solve hundreds of problems. But it is actually more valuable to focus on a handful of problems and get a thorough understanding of each data structure and algorithm and how to apply them.</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/top-10-sorting-algorithms/?utm_source=criodo-blog"><div class="kg-bookmark-content"><div class="kg-bookmark-title">10 Best Sorting Algorithms You Must Know About</div><div class="kg-bookmark-description">What is the fastest sorting algorithm? Which one is the simplest sorting algorithm? Why do we even use sorting algorithms? Get all your answers.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="Top 10 Data Structures Interview Questions (2023)"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Sandipan Das</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2022/02/Sorting-Algorithms.png" alt="Top 10 Data Structures Interview Questions (2023)"></div></a></figure><p>Once you take this approach to learning, you will find that you can segregate problems into different types and each of these will have the same approach and algorithm that can be used. </p><p>This blog will introduce you to frequently asked DSA interview questions in some of the top IT companies in the world.</p><p>List of Questions</p><ol><li><a href="https://www.crio.do/blog/data-structures-interview-questions#1-trapping-rainwater">Trapping Rainwater</a></li><li><a href="https://www.crio.do/blog/data-structures-interview-questions#2-rat-in-a-maze">Rat in a Maze</a></li><li><a href="https://www.crio.do/blog/data-structures-interview-questions#3-house-robber">House Robber</a></li><li><a href="https://www.crio.do/blog/data-structures-interview-questions#4-merge-k-sorted-linked-lists">Merge K sorted linked lists</a></li><li><a href="https://www.crio.do/blog/data-structures-interview-questions#5-valid-parentheses">Valid Parentheses</a></li><li><a href="https://www.crio.do/blog/data-structures-interview-questions#6-search-a-2d-matrix">Search a 2D Matrix</a></li><li><a href="https://www.crio.do/blog/data-structures-interview-questions#7-number-of-islands">Number of Islands</a></li><li><a href="https://www.crio.do/blog/data-structures-interview-questions#8-merge-intervals">Merge Intervals</a></li><li><a href="https://www.crio.do/blog/data-structures-interview-questions#9-minimize-cash-flow">Minimize Cash Flow</a></li><li><a href="https://www.crio.do/blog/data-structures-interview-questions#10-lru-cache">LRU Cache</a></li></ol><h3 id="1-trapping-rainwater">1. Trapping Rainwater<br></h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Trapping-Rainwater.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1212" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Trapping-Rainwater.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Trapping-Rainwater.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Trapping-Rainwater.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Trapping-Rainwater.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>Steps</strong></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Trapping-Rainwater-Steps.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1331" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Trapping-Rainwater-Steps.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Trapping-Rainwater-Steps.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Trapping-Rainwater-Steps.png 1600w, https://www.crio.do/blog/content/images/2022/03/Trapping-Rainwater-Steps.png 2293w" sizes="(min-width: 720px) 720px"></figure><p>Rainwater can be trapped if there are bars of higher elevations to its left and right. The amount of water that can be trapped is the difference between the minimum of the two higher elevations to the left and right and the elevation in the current bar.</p><p>Here, <strong>two-pointer approach </strong>is used which uses two different pointers, one moving from the left to the right, and another from the right to the left of the elevation map.</p><ol><li>Start with the <strong>left pointer</strong> on the leftmost bar, i.e, initialize <strong>left pointer</strong> to index 0, and the <strong>right pointer</strong> on the rightmost bar i.e., initialize <strong>right pointer</strong> to index n-1. Set the amount of <strong>water stored</strong> to be 0. </li><li>Create two variables <strong>maxLeft</strong><em> </em>and<strong> maxRight</strong><em> </em>to keep track of the highest elevations encountered by the left and right pointer respectively. Initalize <strong>maxLeft</strong> and <strong>maxRight</strong> as 0.</li><li>Traverse the array with these two pointers until they cross each other i,e., <strong><em>While left pointer &lt;= right pointer</em></strong></li></ol><!--kg-card-begin: markdown--><p>a. Find the highest bars on the left and right sides by performing the following  comparisons.</p>
<ul>
<li>If the elevation at <strong>left pointer</strong> is greater than maxLeft, update <strong>maxLeft</strong>.</li>
<li>If the elevation at <strong>right pointer</strong> is greater than maxRight, update <strong>maxRight</strong>.</li>
</ul>
<p>b. There will be two cases at each iteration.</p>
<ul>
<li>If <strong>maxLeft &lt;= maxRight</strong></li>
</ul>
<p>Increment the <strong>water stored</strong> by the difference between maxLeft and the elevation at the left pointer bar.</p>
<p>Increment the <strong>left pointer</strong> by 1.</p>
<ul>
<li>If <strong>maxLeft &gt; maxRight</strong></li>
</ul>
<p>Increment the <strong>water stored</strong> by the difference between maxRight and the elevation at the right pointer bar.</p>
<p>Decrement the <strong>right pointer</strong> by 1.</p>
<!--kg-card-end: markdown--><p>4. Display the <strong>water stored</strong>, which is the required result.</p><h3 id="2-rat-in-a-maze">2. Rat in a Maze<br></h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Rat-in-a-Maze.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1519" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Rat-in-a-Maze.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Rat-in-a-Maze.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Rat-in-a-Maze.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Rat-in-a-Maze.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>Steps</strong> </p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Rat-in-a-Maze-Steps.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1608" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Rat-in-a-Maze-Steps.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Rat-in-a-Maze-Steps.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Rat-in-a-Maze-Steps.png 1600w, https://www.crio.do/blog/content/images/2022/03/Rat-in-a-Maze-Steps.png 2166w" sizes="(min-width: 720px) 720px"></figure><p><strong>Two paths exist for the rat to travel to the destination (3,3)</strong></p><p>We will use the principle of <strong>backtracking</strong> to find all valid paths.</p><ol><li>Create a path matrix of N*N dimensions to keep track of the path that the rat will take. This matrix will be used to store the path that the rat takes by marking the cells it has visited with 1s and the unvisited cells with 0s.</li><li>Start the traversal of the input matrix that represents the maze starting from the rat&#x2019;s initial position (0,0). The rat can traverse in 4 possible ways - either down, up, right, or left. Keep track of the visited cells by marking them as visited in the path matrix.</li><li>If the position &#xA0;(x,y) is out of the matrix, or if it is blocked (0) backtrack to the previous step taken.</li></ol><p>Else,</p><ul><li>Mark (x,y) as visited in the path matrix</li><li>If (x,y) is the destination cell,</li><li>Then</li><li>Print the path taken as a solution (using the path matrix) and backtrack to the previous step</li></ul><p>Else</p><ul><li>Move from (x,y) to (x+1,y) (right), (x-1,y) (left), (x,y+1) (down) (x,y-1) (up), one at a time, and repeat step 4 recursively from each of these positions.</li><li>If these don&#x2019;t lead to the destination cell, unmark (x,y) as visited in the path matrix and backtrack to the previous step.	</li></ul><h3 id="3-house-robber">3. House Robber</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/House-Robber.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1222" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/House-Robber.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/House-Robber.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/House-Robber.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/House-Robber.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>Steps</strong></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/House-Robber-Steps.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="1789" height="1377" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/House-Robber-Steps.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/House-Robber-Steps.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/House-Robber-Steps.png 1600w, https://www.crio.do/blog/content/images/2022/03/House-Robber-Steps.png 1789w" sizes="(min-width: 720px) 720px"></figure><ol><li>There can be no houses so the robber can&apos;t steal any money. There can be just one house, in which case the robber steals money from that house. If there are two or more houses, the robber will try to steal the maximum amount of money without stealing from any two adjacent houses.</li><li>Use an array called dp[ ] with the size equal to the number of houses. Each element of this array will indicate the maximum amount of money that can be stolen from the ith house (index of that element) to the last house.</li></ol><p>To find out the maximum money that can be stolen you need to consider every possible combination of houses from the ith house to the last house. However, this will result in repeatedly calculating certain sub-problems. By storing the result of these subproblems (the maximum money that can be stolen from ith house to the last house) in the dp array, you can optimise the solution. <strong>This is the principle of Dynamic Programming</strong>.</p><p>3. The robber can steal money in two ways as he moves from the first house to the last</p><!--kg-card-begin: markdown--><p>a. He can rob from the current house (i) and skip the next house ( go to the house at i + 2), and from there find the maximum money that can be stolen amongst all the houses that are remaining.</p>
<p>So the robber steals the money from the current house + the maximum money that can be stolen from house i+2 onwards.</p>
<p>b. He can skip the current house and move to the next house (at i + 1) and repeat step 3. So, the robber steals the maximum amount that can be stolen from house i + 1 onwards.</p>
<!--kg-card-end: markdown--><p>4. Now, find the maximum of the values calculated at steps a and b and update the dp array to this value.</p><p><em>Note: If the maximum money that can be stolen at a house i has already been calculated and stored in dp[i], the value is directly used. </em></p><h3 id="4-merge-k-sorted-linked-lists">4. Merge K Sorted Linked Lists</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Merge-K-Sorted-Linked-Lists.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1122" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Merge-K-Sorted-Linked-Lists.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Merge-K-Sorted-Linked-Lists.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Merge-K-Sorted-Linked-Lists.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Merge-K-Sorted-Linked-Lists.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>Steps</strong></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Merge-K-Sorted-Linked-Lists-Steps.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="1789" height="1377" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Merge-K-Sorted-Linked-Lists-Steps.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Merge-K-Sorted-Linked-Lists-Steps.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Merge-K-Sorted-Linked-Lists-Steps.png 1600w, https://www.crio.do/blog/content/images/2022/03/Merge-K-Sorted-Linked-Lists-Steps.png 1789w" sizes="(min-width: 720px) 720px"></figure><ol><li>Pair the K linked lists into groups of 2 and combine each pair in a sorted way with linear <a href="https://www.crio.do/blog/time-complexity-explained/?utm_source=criodo-blog">time complexity</a>.</li><li>A pair of linked lists can be combined by using 2 pointers, each pointer traversing one linked list. Both pointers start at the head node of their respective list and traverse through the nodes till the end. At each step, compare the value at the two nodes and pick the smallest of the nodes. Increment that smaller node pointer while the other pointer stays where it is.</li><li>After the first repetition, K / 2 lists remain, each with a size of 2 * N. In the second duplication, K / 4 linked lists remain, and so on.</li><li>Repeat this process until you have only one linked list left.</li></ol><h3 id="5-valid-parentheses">5. Valid Parentheses</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Valid-Parentheses.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1122" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Valid-Parentheses.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Valid-Parentheses.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Valid-Parentheses.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Valid-Parentheses.png 2400w" sizes="(min-width: 720px) 720px"></figure><p>For a set of parentheses to be valid, they have to be closed in the reverse order in which they have been opened. In other words, the most recently opened bracket has to be closed first. The Last In First Out property of a stack is well suited to handle this. </p><p><strong>Steps</strong></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Valid-Parentheses-Steps.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1540" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Valid-Parentheses-Steps.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Valid-Parentheses-Steps.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Valid-Parentheses-Steps.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Valid-Parentheses-Steps.png 2400w" sizes="(min-width: 720px) 720px"></figure><ol><li>Use a stack to store characters.</li><li>Traverse the given string expression.</li><li>If the current character is an opening bracket, then push it into the stack.</li><li>If the current character is a closing bracket, compare it to the character at the top of the stack by popping from the stack. If they are a pair of opening and closing brackets of the same kind, the brackets are valid and we continue. If not, they are invalid, we can stop at this point and return false.</li><li>After the traversal, if there is an opening bracket left in the stack, then the parentheses are not valid.</li></ol><h3 id="6-search-a-2d-matrix">6. Search a 2D Matrix</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Search-a-2D-Matrix.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1485" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Search-a-2D-Matrix.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Search-a-2D-Matrix.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Search-a-2D-Matrix.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Search-a-2D-Matrix.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>Steps</strong></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Search-a-2D-Matrix-Steps.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="1920" height="3493" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Search-a-2D-Matrix-Steps.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Search-a-2D-Matrix-Steps.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Search-a-2D-Matrix-Steps.png 1600w, https://www.crio.do/blog/content/images/2022/03/Search-a-2D-Matrix-Steps.png 1920w" sizes="(min-width: 720px) 720px"></figure><p>Binary Search is the optimal solution for this problem as we have a sorted matrix. You can perform Binary Search at the middle column of the sorted matrix. If the search element is less than the middle element of the middle column, then you can eliminate all the rows following that element. The vice versa can be done if the search element is greater than the middle element, which makes searching easier.</p><ol><li>Perform binary search on the middle column of the matrix. If at any iteration, the search element is equal to the middle column element being compared, the search is successful. Else, continue binary search until only two rows are remaining.</li><li>Compare the search element with the middle elements of the two remaining rows. Now, there are four cases that may arise</li></ol><ul><li>If the search element is equal to either of the middle elements, the search is successful.</li><li>If the search element is lesser than both the middle elements, perform binary search on the first half of the first row.</li><li>If the search element is between the middle elements, perform binary search first on the second half of the first row, and if the search element is not found, perform binary search on the first half of the second row.</li><li>If the search element is greater than both the middle elements, perform binary search on the second half of the second row.</li></ul><p>3. If the search element is still not found, label the search as unsuccessful.</p><p>4. Use a nested loop. An outer loop for the row and an inner loop for the column.</p><h3 id="7-number-of-islands">7. Number of Islands</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Number-of-Islands.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1122" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Number-of-Islands.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Number-of-Islands.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Number-of-Islands.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Number-of-Islands.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>Steps</strong></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Number-of-Islands-Steps.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="998" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Number-of-Islands-Steps.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Number-of-Islands-Steps.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Number-of-Islands-Steps.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Number-of-Islands-Steps.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>There are 3 islands in this matrix</strong></p><p>Since two pieces of land are connected only if they are vertically or horizontally adjacent to each other, the matrix can be treated as an undirected graph, with an edge between two horizontally or vertically adjacent nodes of value 1.</p><p>Because all the nodes in an island are connected, a graph search algorithm can be used to visit all the nodes of an island by starting at any island node. Any graph search algorithm such as Depth First Search or Breadth First Search can be used to solve this problem.</p><p>Here Depth First Search is used as the graph search algorithm.</p><ol><li>Treat the 2D matrix as an undirected graph with an edge between two horizontally or vertically adjacent nodes of value 1.</li><li>Linear scan the 2D matrix.</li><li>Depth-first search is initiated upon finding an unvisited node 1. This node is taken as the root node.</li><li>During DFS, set every visited node as 0, to account for visited nodes.</li><li>The number of root nodes that trigger DFS would be the number of islands.</li></ol><h3 id="8-merge-intervals">8. Merge Intervals</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Merge-Intervals.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1122" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Merge-Intervals.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Merge-Intervals.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Merge-Intervals.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Merge-Intervals.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>Steps</strong></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Merge-Intervals-Steps.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="643" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Merge-Intervals-Steps.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Merge-Intervals-Steps.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Merge-Intervals-Steps.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Merge-Intervals-Steps.png 2400w" sizes="(min-width: 720px) 720px"></figure><p>If you have a sorted list of intervals (sorted by their start time), with the first i intervals non overlapping, then the (i + 1)th interval can only overlap with the ith interval. Hence, if you push the first i intervals into a stack, then only the interval at the top of the stack is required for further comparison.</p><ol><li>Sort the given intervals in increasing order of their starting time.</li><li>Create an empty stack and start traversing the list of intervals.</li><li>For each interval,</li></ol><ul><li>Push the current interval into the stack only if the stack is empty or the top interval in the stack does not overlap with it.</li><li>If the current interval overlaps with the top interval of the stack, that is, the starting time of the current interval is less than the ending time of the stack top interval, update the ending time of the stack top interval as the ending time of the current interval.</li></ul><p>4. The stack now contains the list of merged intervals none of which overlap.</p><h3 id="9-minimize-cash-flow">9. Minimize Cash Flow</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Minimize-Cash-Flow.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1243" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Minimize-Cash-Flow.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Minimize-Cash-Flow.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Minimize-Cash-Flow.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Minimize-Cash-Flow.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>Steps</strong></p><!--kg-card-begin: markdown--><ol>
<li>Calculate the total amount of each person as -</li>
</ol>
<p>Net amount at person i = Sum of all money i receives - Sum of all money i pays</p>
<ol start="2">
<li>Find two persons with the maximum and minimum net amount. Let the person with the maximum net amount be maxReceiver and the person with the minimum net amount be maxPayer.</li>
<li>Find the absolute minimum of maxReceiver and maxPayer. Let this amount be payment &#x2018;x&#x2019;.</li>
<li>maxPayer will pay &#x2018;x&#x2019; to maxReceiver. X will be added to maxPayer&#x2019;s net amount and subtracted from maxReceiver&#x2019;s net amount.</li>
<li>Repeat steps 2 to 4 until all the net amounts become zero.</li>
</ol>
<!--kg-card-end: markdown--><h3 id="10-lru-cache">10. LRU Cache</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/LRU-Cache.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1324" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/LRU-Cache.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/LRU-Cache.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/LRU-Cache.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/LRU-Cache.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>Steps</strong></p><p>Least Recently Used (LRU) is a common caching strategy. It implements a policy to evict elements from the <a href="https://www.crio.do/blog/cache-memory-explained/?utm_source=criodo-blog">cache</a>. When the cache is full and new elements need to be added, it evicts the least recently used items first.</p><p><em>Also read,</em></p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/cache-memory-explained/?utm_source=criodo-blog"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Cache Memory Explained for Developers</div><div class="kg-bookmark-description">Everything you need to know about cached data, cache memory, cache vs cookies, uses and importance of cache.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="Top 10 Data Structures Interview Questions (2023)"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Kevin Paulose</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/07/Cache-memory.png" alt="Top 10 Data Structures Interview Questions (2023)"></div></a></figure><p>Take an example of a cache that has a capacity of 4 . The elements 1, 2, 3, 4 are cached with 1 being the first element to be cached and 4 the last element.</p><p>The cache state after first access of all four elements</p><p>1	2	3	4</p><p>Say you need to cache a new element 5.</p><p>In LRU cache, the least recently used element should be evicted in case a new element needs to be added.</p><p>So, 1 is removed and 5 is added to the cache. Now the cache has the elements</p><p>2, 3, 4, 5</p><p>.</p><p>A cache has to be able to access and retrieve the data in constant time. This can be achieved using the following data structures</p><p>Queue (representing the cache) - The maximum size of the queue will be equal to the cache size . The most recently used elements will be near the front end and the least recent elements will be near the rear end. A doubly linked list is used to implement this queue over a singly linked list because a doubly linked list can delete a node given its address, in constant time whereas a singly linked list achieves this in linear time.</p><p>Hashmap - Use a hashmap to access the node address of the doubly linked list which corresponds to a particular element in constant time.The hashmap will contain the element as key and address of the corresponding node as value.</p><ol><li>When an element is referenced, try to lookup the cache by using the corresponding node address from the hash. The required element may be in the cache. If it is in the cache, &#xA0;detach the particular node from the list and attach it to the front of the queue.</li><li>If the required element is not in cache, attach a new node to the front of the queue and write the corresponding node address in the hash.</li><li>If the queue is full, delete a node from the rear of the queue, and add the new node to the front of the queue. Update the hash.</li></ol><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><h3 id="conclusion">Conclusion</h3><p>Hope this blog helped you learn to apply different data structures and algorithms using the problem statements asked in interviews. Only some of the frequently asked questions were picked for this blog. But there are many more such problems you can find and practice. Crio&#x2019;s <a href="https://www.crio.do/software-development-fellowship-program/#data-structures?utm_source=criodo-blog&amp;utm_medium=dsiq">DSA</a> packs are a great place to start and master all the <a href="https://www.crio.do/blog/tag/data-structures-and-algorithms/?utm_source=criodo-blog">data structures and algorithms</a>.<br><br></p>]]></content:encoded></item><item><title><![CDATA[Top 10 Data Structures Interview Questions (2023)]]></title><description><![CDATA[Coding interviews are comprised mainly of Data Structures and Algorithms. Here are the most commonly asked data structures interview questions and answers for freshers. ]]></description><link>https://www.crio.do/blog/data-structures-interview-questions/</link><guid isPermaLink="false">62219e90c50e7c6cd272ce02</guid><category><![CDATA[Data Structures and Algorithms]]></category><dc:creator><![CDATA[Abheetha Pradhan]]></dc:creator><pubDate>Fri, 14 Oct 2022 14:15:00 GMT</pubDate><media:content url="https://www.crio.do/blog/content/images/2022/03/Data-Structures-Interview-Questions.png" medium="image"/><content:encoded><![CDATA[<figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><img src="https://www.crio.do/blog/content/images/2022/03/Data-Structures-Interview-Questions.png" alt="Top 10 Data Structures Interview Questions (2023)"><p>Why do you need knowledge of data structures and algorithms?</p><p><a href="https://www.crio.do/blog/tag/data-structures-and-algorithms/?utm_source=criodo-blog">Data structures and Algorithms</a> are techniques used to write efficient code for a given problem, much like how you need music theory to master an instrument. <strong>To be a good programmer you need to learn to use the right data structure and algorithm for a given problem. </strong></p><p>Say, you need to travel to a particular spot in your city. You take a car to travel to the spot but later discover that taking the metro would have been faster and cheaper. Similarly, insufficient knowledge in DSA can lead you to write inefficient code. </p><p>In interviews, an interviewer will test you on the basis of how quickly you come up with the solution, how efficient your code is, and they can go on to ask you in-depth questions about the data structure or algorithm you&#x2019;ve used to solve the problem. </p><p>The popular opinion for mastering Data Structures and Algorithms is to solve hundreds of problems. But it is actually more valuable to focus on a handful of problems and get a thorough understanding of each data structure and algorithm and how to apply them.</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/top-10-sorting-algorithms/?utm_source=criodo-blog"><div class="kg-bookmark-content"><div class="kg-bookmark-title">10 Best Sorting Algorithms You Must Know About</div><div class="kg-bookmark-description">What is the fastest sorting algorithm? Which one is the simplest sorting algorithm? Why do we even use sorting algorithms? Get all your answers.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="Top 10 Data Structures Interview Questions (2023)"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Sandipan Das</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2022/02/Sorting-Algorithms.png" alt="Top 10 Data Structures Interview Questions (2023)"></div></a></figure><p>Once you take this approach to learning, you will find that you can segregate problems into different types and each of these will have the same approach and algorithm that can be used. </p><p>This blog will introduce you to frequently asked DSA interview questions in some of the top IT companies in the world.</p><p>List of Questions</p><ol><li><a href="https://www.crio.do/blog/data-structures-interview-questions#1-trapping-rainwater">Trapping Rainwater</a></li><li><a href="https://www.crio.do/blog/data-structures-interview-questions#2-rat-in-a-maze">Rat in a Maze</a></li><li><a href="https://www.crio.do/blog/data-structures-interview-questions#3-house-robber">House Robber</a></li><li><a href="https://www.crio.do/blog/data-structures-interview-questions#4-merge-k-sorted-linked-lists">Merge K sorted linked lists</a></li><li><a href="https://www.crio.do/blog/data-structures-interview-questions#5-valid-parentheses">Valid Parentheses</a></li><li><a href="https://www.crio.do/blog/data-structures-interview-questions#6-search-a-2d-matrix">Search a 2D Matrix</a></li><li><a href="https://www.crio.do/blog/data-structures-interview-questions#7-number-of-islands">Number of Islands</a></li><li><a href="https://www.crio.do/blog/data-structures-interview-questions#8-merge-intervals">Merge Intervals</a></li><li><a href="https://www.crio.do/blog/data-structures-interview-questions#9-minimize-cash-flow">Minimize Cash Flow</a></li><li><a href="https://www.crio.do/blog/data-structures-interview-questions#10-lru-cache">LRU Cache</a></li></ol><h3 id="1-trapping-rainwater">1. Trapping Rainwater<br></h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Trapping-Rainwater.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1212" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Trapping-Rainwater.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Trapping-Rainwater.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Trapping-Rainwater.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Trapping-Rainwater.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>Steps</strong></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Trapping-Rainwater-Steps.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1331" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Trapping-Rainwater-Steps.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Trapping-Rainwater-Steps.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Trapping-Rainwater-Steps.png 1600w, https://www.crio.do/blog/content/images/2022/03/Trapping-Rainwater-Steps.png 2293w" sizes="(min-width: 720px) 720px"></figure><p>Rainwater can be trapped if there are bars of higher elevations to its left and right. The amount of water that can be trapped is the difference between the minimum of the two higher elevations to the left and right and the elevation in the current bar.</p><p>Here, <strong>two-pointer approach </strong>is used which uses two different pointers, one moving from the left to the right, and another from the right to the left of the elevation map.</p><ol><li>Start with the <strong>left pointer</strong> on the leftmost bar, i.e, initialize <strong>left pointer</strong> to index 0, and the <strong>right pointer</strong> on the rightmost bar i.e., initialize <strong>right pointer</strong> to index n-1. Set the amount of <strong>water stored</strong> to be 0. </li><li>Create two variables <strong>maxLeft</strong><em> </em>and<strong> maxRight</strong><em> </em>to keep track of the highest elevations encountered by the left and right pointer respectively. Initalize <strong>maxLeft</strong> and <strong>maxRight</strong> as 0.</li><li>Traverse the array with these two pointers until they cross each other i,e., <strong><em>While left pointer &lt;= right pointer</em></strong></li></ol><!--kg-card-begin: markdown--><p>a. Find the highest bars on the left and right sides by performing the following  comparisons.</p>
<ul>
<li>If the elevation at <strong>left pointer</strong> is greater than maxLeft, update <strong>maxLeft</strong>.</li>
<li>If the elevation at <strong>right pointer</strong> is greater than maxRight, update <strong>maxRight</strong>.</li>
</ul>
<p>b. There will be two cases at each iteration.</p>
<ul>
<li>If <strong>maxLeft &lt;= maxRight</strong></li>
</ul>
<p>Increment the <strong>water stored</strong> by the difference between maxLeft and the elevation at the left pointer bar.</p>
<p>Increment the <strong>left pointer</strong> by 1.</p>
<ul>
<li>If <strong>maxLeft &gt; maxRight</strong></li>
</ul>
<p>Increment the <strong>water stored</strong> by the difference between maxRight and the elevation at the right pointer bar.</p>
<p>Decrement the <strong>right pointer</strong> by 1.</p>
<!--kg-card-end: markdown--><p>4. Display the <strong>water stored</strong>, which is the required result.</p><h3 id="2-rat-in-a-maze">2. Rat in a Maze<br></h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Rat-in-a-Maze.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1519" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Rat-in-a-Maze.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Rat-in-a-Maze.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Rat-in-a-Maze.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Rat-in-a-Maze.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>Steps</strong> </p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Rat-in-a-Maze-Steps.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1608" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Rat-in-a-Maze-Steps.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Rat-in-a-Maze-Steps.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Rat-in-a-Maze-Steps.png 1600w, https://www.crio.do/blog/content/images/2022/03/Rat-in-a-Maze-Steps.png 2166w" sizes="(min-width: 720px) 720px"></figure><p><strong>Two paths exist for the rat to travel to the destination (3,3)</strong></p><p>We will use the principle of <strong>backtracking</strong> to find all valid paths.</p><ol><li>Create a path matrix of N*N dimensions to keep track of the path that the rat will take. This matrix will be used to store the path that the rat takes by marking the cells it has visited with 1s and the unvisited cells with 0s.</li><li>Start the traversal of the input matrix that represents the maze starting from the rat&#x2019;s initial position (0,0). The rat can traverse in 4 possible ways - either down, up, right, or left. Keep track of the visited cells by marking them as visited in the path matrix.</li><li>If the position &#xA0;(x,y) is out of the matrix, or if it is blocked (0) backtrack to the previous step taken.</li></ol><p>Else,</p><ul><li>Mark (x,y) as visited in the path matrix</li><li>If (x,y) is the destination cell,</li><li>Then</li><li>Print the path taken as a solution (using the path matrix) and backtrack to the previous step</li></ul><p>Else</p><ul><li>Move from (x,y) to (x+1,y) (right), (x-1,y) (left), (x,y+1) (down) (x,y-1) (up), one at a time, and repeat step 4 recursively from each of these positions.</li><li>If these don&#x2019;t lead to the destination cell, unmark (x,y) as visited in the path matrix and backtrack to the previous step.	</li></ul><h3 id="3-house-robber">3. House Robber</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/House-Robber.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1222" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/House-Robber.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/House-Robber.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/House-Robber.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/House-Robber.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>Steps</strong></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/House-Robber-Steps.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="1789" height="1377" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/House-Robber-Steps.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/House-Robber-Steps.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/House-Robber-Steps.png 1600w, https://www.crio.do/blog/content/images/2022/03/House-Robber-Steps.png 1789w" sizes="(min-width: 720px) 720px"></figure><ol><li>There can be no houses so the robber can&apos;t steal any money. There can be just one house, in which case the robber steals money from that house. If there are two or more houses, the robber will try to steal the maximum amount of money without stealing from any two adjacent houses.</li><li>Use an array called dp[ ] with the size equal to the number of houses. Each element of this array will indicate the maximum amount of money that can be stolen from the ith house (index of that element) to the last house.</li></ol><p>To find out the maximum money that can be stolen you need to consider every possible combination of houses from the ith house to the last house. However, this will result in repeatedly calculating certain sub-problems. By storing the result of these subproblems (the maximum money that can be stolen from ith house to the last house) in the dp array, you can optimise the solution. <strong>This is the principle of Dynamic Programming</strong>.</p><p>3. The robber can steal money in two ways as he moves from the first house to the last</p><!--kg-card-begin: markdown--><p>a. He can rob from the current house (i) and skip the next house ( go to the house at i + 2), and from there find the maximum money that can be stolen amongst all the houses that are remaining.</p>
<p>So the robber steals the money from the current house + the maximum money that can be stolen from house i+2 onwards.</p>
<p>b. He can skip the current house and move to the next house (at i + 1) and repeat step 3. So, the robber steals the maximum amount that can be stolen from house i + 1 onwards.</p>
<!--kg-card-end: markdown--><p>4. Now, find the maximum of the values calculated at steps a and b and update the dp array to this value.</p><p><em>Note: If the maximum money that can be stolen at a house i has already been calculated and stored in dp[i], the value is directly used. </em></p><h3 id="4-merge-k-sorted-linked-lists">4. Merge K Sorted Linked Lists</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Merge-K-Sorted-Linked-Lists.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1122" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Merge-K-Sorted-Linked-Lists.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Merge-K-Sorted-Linked-Lists.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Merge-K-Sorted-Linked-Lists.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Merge-K-Sorted-Linked-Lists.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>Steps</strong></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Merge-K-Sorted-Linked-Lists-Steps.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="1789" height="1377" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Merge-K-Sorted-Linked-Lists-Steps.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Merge-K-Sorted-Linked-Lists-Steps.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Merge-K-Sorted-Linked-Lists-Steps.png 1600w, https://www.crio.do/blog/content/images/2022/03/Merge-K-Sorted-Linked-Lists-Steps.png 1789w" sizes="(min-width: 720px) 720px"></figure><ol><li>Pair the K linked lists into groups of 2 and combine each pair in a sorted way with linear <a href="https://www.crio.do/blog/time-complexity-explained/?utm_source=criodo-blog">time complexity</a>.</li><li>A pair of linked lists can be combined by using 2 pointers, each pointer traversing one linked list. Both pointers start at the head node of their respective list and traverse through the nodes till the end. At each step, compare the value at the two nodes and pick the smallest of the nodes. Increment that smaller node pointer while the other pointer stays where it is.</li><li>After the first repetition, K / 2 lists remain, each with a size of 2 * N. In the second duplication, K / 4 linked lists remain, and so on.</li><li>Repeat this process until you have only one linked list left.</li></ol><h3 id="5-valid-parentheses">5. Valid Parentheses</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Valid-Parentheses.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1122" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Valid-Parentheses.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Valid-Parentheses.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Valid-Parentheses.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Valid-Parentheses.png 2400w" sizes="(min-width: 720px) 720px"></figure><p>For a set of parentheses to be valid, they have to be closed in the reverse order in which they have been opened. In other words, the most recently opened bracket has to be closed first. The Last In First Out property of a stack is well suited to handle this. </p><p><strong>Steps</strong></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Valid-Parentheses-Steps.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1540" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Valid-Parentheses-Steps.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Valid-Parentheses-Steps.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Valid-Parentheses-Steps.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Valid-Parentheses-Steps.png 2400w" sizes="(min-width: 720px) 720px"></figure><ol><li>Use a stack to store characters.</li><li>Traverse the given string expression.</li><li>If the current character is an opening bracket, then push it into the stack.</li><li>If the current character is a closing bracket, compare it to the character at the top of the stack by popping from the stack. If they are a pair of opening and closing brackets of the same kind, the brackets are valid and we continue. If not, they are invalid, we can stop at this point and return false.</li><li>After the traversal, if there is an opening bracket left in the stack, then the parentheses are not valid.</li></ol><h3 id="6-search-a-2d-matrix">6. Search a 2D Matrix</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Search-a-2D-Matrix.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1485" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Search-a-2D-Matrix.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Search-a-2D-Matrix.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Search-a-2D-Matrix.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Search-a-2D-Matrix.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>Steps</strong></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Search-a-2D-Matrix-Steps.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="1920" height="3493" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Search-a-2D-Matrix-Steps.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Search-a-2D-Matrix-Steps.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Search-a-2D-Matrix-Steps.png 1600w, https://www.crio.do/blog/content/images/2022/03/Search-a-2D-Matrix-Steps.png 1920w" sizes="(min-width: 720px) 720px"></figure><p>Binary Search is the optimal solution for this problem as we have a sorted matrix. You can perform Binary Search at the middle column of the sorted matrix. If the search element is less than the middle element of the middle column, then you can eliminate all the rows following that element. The vice versa can be done if the search element is greater than the middle element, which makes searching easier.</p><ol><li>Perform binary search on the middle column of the matrix. If at any iteration, the search element is equal to the middle column element being compared, the search is successful. Else, continue binary search until only two rows are remaining.</li><li>Compare the search element with the middle elements of the two remaining rows. Now, there are four cases that may arise</li></ol><ul><li>If the search element is equal to either of the middle elements, the search is successful.</li><li>If the search element is lesser than both the middle elements, perform binary search on the first half of the first row.</li><li>If the search element is between the middle elements, perform binary search first on the second half of the first row, and if the search element is not found, perform binary search on the first half of the second row.</li><li>If the search element is greater than both the middle elements, perform binary search on the second half of the second row.</li></ul><p>3. If the search element is still not found, label the search as unsuccessful.</p><p>4. Use a nested loop. An outer loop for the row and an inner loop for the column.</p><h3 id="7-number-of-islands">7. Number of Islands</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Number-of-Islands.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1122" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Number-of-Islands.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Number-of-Islands.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Number-of-Islands.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Number-of-Islands.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>Steps</strong></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Number-of-Islands-Steps.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="998" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Number-of-Islands-Steps.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Number-of-Islands-Steps.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Number-of-Islands-Steps.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Number-of-Islands-Steps.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>There are 3 islands in this matrix</strong></p><p>Since two pieces of land are connected only if they are vertically or horizontally adjacent to each other, the matrix can be treated as an undirected graph, with an edge between two horizontally or vertically adjacent nodes of value 1.</p><p>Because all the nodes in an island are connected, a graph search algorithm can be used to visit all the nodes of an island by starting at any island node. Any graph search algorithm such as Depth First Search or Breadth First Search can be used to solve this problem.</p><p>Here Depth First Search is used as the graph search algorithm.</p><ol><li>Treat the 2D matrix as an undirected graph with an edge between two horizontally or vertically adjacent nodes of value 1.</li><li>Linear scan the 2D matrix.</li><li>Depth-first search is initiated upon finding an unvisited node 1. This node is taken as the root node.</li><li>During DFS, set every visited node as 0, to account for visited nodes.</li><li>The number of root nodes that trigger DFS would be the number of islands.</li></ol><h3 id="8-merge-intervals">8. Merge Intervals</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Merge-Intervals.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1122" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Merge-Intervals.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Merge-Intervals.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Merge-Intervals.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Merge-Intervals.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>Steps</strong></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Merge-Intervals-Steps.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="643" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Merge-Intervals-Steps.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Merge-Intervals-Steps.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Merge-Intervals-Steps.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Merge-Intervals-Steps.png 2400w" sizes="(min-width: 720px) 720px"></figure><p>If you have a sorted list of intervals (sorted by their start time), with the first i intervals non overlapping, then the (i + 1)th interval can only overlap with the ith interval. Hence, if you push the first i intervals into a stack, then only the interval at the top of the stack is required for further comparison.</p><ol><li>Sort the given intervals in increasing order of their starting time.</li><li>Create an empty stack and start traversing the list of intervals.</li><li>For each interval,</li></ol><ul><li>Push the current interval into the stack only if the stack is empty or the top interval in the stack does not overlap with it.</li><li>If the current interval overlaps with the top interval of the stack, that is, the starting time of the current interval is less than the ending time of the stack top interval, update the ending time of the stack top interval as the ending time of the current interval.</li></ul><p>4. The stack now contains the list of merged intervals none of which overlap.</p><h3 id="9-minimize-cash-flow">9. Minimize Cash Flow</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/Minimize-Cash-Flow.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1243" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/Minimize-Cash-Flow.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/Minimize-Cash-Flow.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/Minimize-Cash-Flow.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/Minimize-Cash-Flow.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>Steps</strong></p><!--kg-card-begin: markdown--><ol>
<li>Calculate the total amount of each person as -</li>
</ol>
<p>Net amount at person i = Sum of all money i receives - Sum of all money i pays</p>
<ol start="2">
<li>Find two persons with the maximum and minimum net amount. Let the person with the maximum net amount be maxReceiver and the person with the minimum net amount be maxPayer.</li>
<li>Find the absolute minimum of maxReceiver and maxPayer. Let this amount be payment &#x2018;x&#x2019;.</li>
<li>maxPayer will pay &#x2018;x&#x2019; to maxReceiver. X will be added to maxPayer&#x2019;s net amount and subtracted from maxReceiver&#x2019;s net amount.</li>
<li>Repeat steps 2 to 4 until all the net amounts become zero.</li>
</ol>
<!--kg-card-end: markdown--><h3 id="10-lru-cache">10. LRU Cache</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/03/LRU-Cache.png" class="kg-image" alt="Top 10 Data Structures Interview Questions (2023)" loading="lazy" width="2000" height="1324" srcset="https://www.crio.do/blog/content/images/size/w600/2022/03/LRU-Cache.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/03/LRU-Cache.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/03/LRU-Cache.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/03/LRU-Cache.png 2400w" sizes="(min-width: 720px) 720px"></figure><p><strong>Steps</strong></p><p>Least Recently Used (LRU) is a common caching strategy. It implements a policy to evict elements from the <a href="https://www.crio.do/blog/cache-memory-explained/?utm_source=criodo-blog">cache</a>. When the cache is full and new elements need to be added, it evicts the least recently used items first.</p><p><em>Also read,</em></p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/cache-memory-explained/?utm_source=criodo-blog"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Cache Memory Explained for Developers</div><div class="kg-bookmark-description">Everything you need to know about cached data, cache memory, cache vs cookies, uses and importance of cache.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="Top 10 Data Structures Interview Questions (2023)"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Kevin Paulose</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/07/Cache-memory.png" alt="Top 10 Data Structures Interview Questions (2023)"></div></a></figure><p>Take an example of a cache that has a capacity of 4 . The elements 1, 2, 3, 4 are cached with 1 being the first element to be cached and 4 the last element.</p><p>The cache state after first access of all four elements</p><p>1	2	3	4</p><p>Say you need to cache a new element 5.</p><p>In LRU cache, the least recently used element should be evicted in case a new element needs to be added.</p><p>So, 1 is removed and 5 is added to the cache. Now the cache has the elements</p><p>2, 3, 4, 5</p><p>.</p><p>A cache has to be able to access and retrieve the data in constant time. This can be achieved using the following data structures</p><p>Queue (representing the cache) - The maximum size of the queue will be equal to the cache size . The most recently used elements will be near the front end and the least recent elements will be near the rear end. A doubly linked list is used to implement this queue over a singly linked list because a doubly linked list can delete a node given its address, in constant time whereas a singly linked list achieves this in linear time.</p><p>Hashmap - Use a hashmap to access the node address of the doubly linked list which corresponds to a particular element in constant time.The hashmap will contain the element as key and address of the corresponding node as value.</p><ol><li>When an element is referenced, try to lookup the cache by using the corresponding node address from the hash. The required element may be in the cache. If it is in the cache, &#xA0;detach the particular node from the list and attach it to the front of the queue.</li><li>If the required element is not in cache, attach a new node to the front of the queue and write the corresponding node address in the hash.</li><li>If the queue is full, delete a node from the rear of the queue, and add the new node to the front of the queue. Update the hash.</li></ol><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><h3 id="conclusion">Conclusion</h3><p>Hope this blog helped you learn to apply different data structures and algorithms using the problem statements asked in interviews. Only some of the frequently asked questions were picked for this blog. But there are many more such problems you can find and practice. Crio&#x2019;s <a href="https://www.crio.do/software-development-fellowship-program/#data-structures?utm_source=criodo-blog&amp;utm_medium=dsiq">DSA</a> packs are a great place to start and master all the <a href="https://www.crio.do/blog/tag/data-structures-and-algorithms/?utm_source=criodo-blog">data structures and algorithms</a>.<br><br></p>]]></content:encoded></item><item><title><![CDATA[Master Insertion Sort Before Your Next Big Interview]]></title><description><![CDATA[Learn the details of insertion sort and how you can use it effectively to sort your dataset]]></description><link>https://www.crio.do/blog/insertion-sort-2/</link><guid isPermaLink="false">66c783bc134c11095afa9308</guid><category><![CDATA[Data Structures and Algorithms]]></category><dc:creator><![CDATA[Harshita Bansal]]></dc:creator><pubDate>Thu, 29 Sep 2022 05:51:00 GMT</pubDate><media:content url="https://www.crio.do/blog/content/images/2022/02/Insertion-Sort.png" medium="image"/><content:encoded><![CDATA[<img src="https://www.crio.do/blog/content/images/2022/02/Insertion-Sort.png" alt="Master Insertion Sort Before Your Next Big Interview"><p>Most programmers often feel the need to sort the data provided to them. Sorted data is easier to understand and process.</p><p>As resources become increasingly limited and time more valuable, the most efficient sorting mechanism must be implemented based on the characteristics of the data provided.</p><h3 id="various-types-of-sorting-mechanisms-include">Various types of sorting mechanisms include:</h3><ol><li><a href="https://www.crio.do/blog/quick-sort/?utm_source=criodo-blog">Quick Sort</a></li><li>Bubble Sort</li><li><a href="https://www.crio.do/blog/merge-sort-algorithm/?utm_source=criodo-blog">Merge Sort</a></li><li>Insertion Sort</li><li>Selection Sort</li><li>Heap Sort.</li><li>Radix Sort</li><li>Bucket Sort</li></ol><p>This blog covers the fundamentals to get you started with<strong> insertion sort</strong>. Before moving forward, make sure you have gone through the earlier blog on <a href="https://www.crio.do/blog/top-10-sorting-algorithms/?utm_source=criodo-blog">10 best sorting algorithms</a> to easily grasp the following sections.</p><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><h2 id="why-insertion-sort">Why insertion sort?</h2><p>Before diving into the technical details of insertion sort, consider this example:</p><p>You and your pet dog (let&#x2019;s call him Fluffy) are participating in a competition. <br>To win, Fluffy must run to a basket, pick a bone and give it to you, while you need to arrange them in increasing order of length, all of it as quickly as possible. <br>Suppose Fluffy takes 60 seconds to bring a bone, and you need 10 seconds to sort it into its proper position. One approach would be to wait for Fluffy to stack all the bones near you and then sort them. </p><p>For 10 bones, this approach takes (60+10)*10 = 700 seconds. </p><p>Another possible approach would be to sort each bone as it comes into its proper position. This approach takes 60*10 = 600 seconds. That is 1 min 40 sec lesser! Yay!</p><p>Insertion sort does the same. It places a new bone in its proper position in an already sorted array (or subarray, as we will see further). </p><p>Now replace the dog, bone, and yourself with a hard drive, data, and a CPU. While transferring data from a slow hard drive to a CPU, data transfer may take more time than data processing at the CPU. Hence, to avoid wastage of CPU cycles, it is good to keep sorting data alongside and add new data to the sorted data. </p><p>Now let us study the process of insertion sort in detail.</p><h2 id="what-is-insertion-sort">What is insertion sort?</h2><p>Insertion sort is a sorting method that works by shifting each element in the array one at a time. It iterates through the input elements, expanding the sorted array each time by comparing the current element to the sorted array&apos;s greatest value. </p><p>If the current element is greater, it remains in place and continues to the next element; otherwise, it locates the element&apos;s appropriate location in the sorted array and transfers it there.</p><p>Finally, it moves any elements in the sorted array that are greater than the current element one place forward.</p><h3 id="try-it-yourself">Try it yourself</h3><p>Insertion sort strongly resembles how we sort playing cards. To understand how, simply pick every subsequent card from a deck and place it in its proper position by comparing its value. </p><hr><p>Another real-world example of insertion sort is how tailors arrange shirts in a closet. They always keep them in sorted order of size so that they can insert new shirts into the proper spot very quickly by shifting existing shirts forward to make room for the new shirt.</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Insertion-sort-example.png" class="kg-image" alt="Master Insertion Sort Before Your Next Big Interview" loading="lazy" width="1920" height="1812" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Insertion-sort-example.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Insertion-sort-example.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/Insertion-sort-example.png 1600w, https://www.crio.do/blog/content/images/2022/02/Insertion-sort-example.png 1920w" sizes="(min-width: 720px) 720px"></figure><h2 id="insertion-sort-algorithm">Insertion sort algorithm</h2><p>Step 1: The first element is assumed to be already sorted</p><p>Step 2: Select the next element.</p><p>Step 3: Compare all elements in the sorted sublist with the element to be sorted.</p><p>Step 4: Shift all elements in the sorted sub-list that are greater than the value to be sorted.</p><p>Step 5: Fill in the value.</p><p>Step 6: Continue until the list is sorted.</p><h2 id="insertion-sort-pseudocode">Insertion sort pseudocode</h2><p>Assume that the first element is already sorted, and begin the iteration from index = 1 (in a zero-based array).<br></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/07/Screenshot-2021-07-08-at-12.41.04-PM.png" class="kg-image" alt="Master Insertion Sort Before Your Next Big Interview" loading="lazy" width="746" height="167" srcset="https://www.crio.do/blog/content/images/size/w600/2021/07/Screenshot-2021-07-08-at-12.41.04-PM.png 600w, https://www.crio.do/blog/content/images/2021/07/Screenshot-2021-07-08-at-12.41.04-PM.png 746w" sizes="(min-width: 720px) 720px"></figure><p>This algorithm can also be implemented recursively, such that the function calls itself, as follows:<br></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/07/Screenshot-2021-07-08-at-12.42.41-PM.png" class="kg-image" alt="Master Insertion Sort Before Your Next Big Interview" loading="lazy" width="746" height="167" srcset="https://www.crio.do/blog/content/images/size/w600/2021/07/Screenshot-2021-07-08-at-12.42.41-PM.png 600w, https://www.crio.do/blog/content/images/2021/07/Screenshot-2021-07-08-at-12.42.41-PM.png 746w" sizes="(min-width: 720px) 720px"></figure><p>Now that you know the algorithm and the pseudocode, try implementing insertion sort on your own. You may take help from the code snippets provided. Feel free to reach out to us in the comments below in case you get stuck.</p><h3 id="insertion-sort-in-c">Insertion sort in C<br></h3><figure class="kg-card kg-image-card"><img src="https://lh5.googleusercontent.com/XL3vqiocjCIAqy5GNkB3yNSSKqnz7sY4LI4WqDT80Xk16qkarj-q7JSQNxmDSyZmJVOs_AkZZjxo2u027_1xch8gmIQJ-yIlXI62z7GRGf5Vx9pkM8b0hUyrZtbeCrp6oobQbO5h" class="kg-image" alt="Master Insertion Sort Before Your Next Big Interview" loading="lazy"></figure><h3 id="insertion-sort-in-c-1">Insertion sort in C++<br></h3><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/M4OQnKGGhXIuXZ2NddgSyL8ZiC5NwL5Ky_esEbP73rFZABIHKp8qhYTtXdkUSTwR0BTkEWaKwAaIBejku_H5beUGHU1pqRh5FX-tuH9QvEzEsoMeoXgsj0PQ94nbko-ngziYaRn7" class="kg-image" alt="Master Insertion Sort Before Your Next Big Interview" loading="lazy"></figure><h3 id="insertion-sort-in-java">Insertion sort in Java<br></h3><figure class="kg-card kg-image-card"><img src="https://lh6.googleusercontent.com/dYiD9n1BleDWutMVjdVqHfJahAFNSDPr-X5kO-P9kyWK9lkcIDlOWWOwmLRmPlQdxKDfOrclWZ7E5VZU4lpgI0d_sMhiXwOhGe4mPPvtf8wakGY6bFBjZMcJPjBu3r12zdjes4Ri" class="kg-image" alt="Master Insertion Sort Before Your Next Big Interview" loading="lazy"></figure><h3 id="insertion-sort-in-python3">Insertion sort in Python3<br></h3><figure class="kg-card kg-image-card"><img src="https://lh3.googleusercontent.com/otketgf7fAFjC5foqDg_n9Sz7i_7XzvOmeFxLiImHa7KXQ3p5zDdpMC9_IW0-4jFh5TtGMeONKQugY1ulFZyfzlOv6ybxNFZHZbMCWSnAnZSLaW1-KR4S7WIX4JuNjvrH1cIi3qi" class="kg-image" alt="Master Insertion Sort Before Your Next Big Interview" loading="lazy"></figure><h2 id="time-complexity-analysis-of-insertion-sort">Time complexity analysis of insertion sort</h2><p>The <strong>best case</strong> input to an insertion sort function is an array sorted in the required order (here, ascending). In such cases, the algorithm simply compares the values of the <em>ith</em> element and the sorted subarray. Thus we get a linear time complexity, i.e., O(n). </p><p>The <strong>worst-case</strong> input is an array sorted in the opposite order (here, descending). In such cases, the algorithm compares the <em>ith</em> elements to every value in the sorted subarray and shifts every element of the subarray one position forward, thus resulting in quadratic time complexity, i.e., O(n2).</p><p>The<strong> average case</strong> complexity of insertion sort is also quadratic. Hence insertion sort is not preferred for large data sets. However, insertion sort is the fastest algorithm for sorting small arrays. Note that while there is no concrete threshold value to define small and large arrays, it may lie anywhere between 10 to 50 elements.</p><h2 id="space-complexity-analysis-of-insertion-sort">Space complexity analysis of insertion sort</h2><p>Space complexity is the same for all cases, i.e., O(1). Hence, no auxiliary memory is required.</p><h2 id="comparison-of-insertion-sort-with-other-sorting-algorithms">Comparison of insertion sort with other sorting algorithms</h2><p>Insertion sort is similar to selection sort; the primary difference is that the <em>ith</em> iteration in insertion sort gives the sorted subarray from the <em>i</em> elements input to it, whereas, in selection sort, the <em>ith</em> iteration gives the <em>i</em> smallest elements in the entire array. </p><p>Although bubble sort has the same time complexity, i.e., O(n2), it is far less efficient than both insertion and selection sort. While some divide-and-conquer algorithms, such as <a href="https://www.crio.do/blog/quick-sort/?utm_source=criodo-blog">Quick Sort</a> and <a href="https://www.crio.do/blog/merge-sort-algorithm/?utm_source=criodo-blog">Merge Sort</a>, outperform insertion sort for larger arrays, non-recursive sorting methods such as insertion sort or selection sort are often quicker for small arrays.</p><h2 id="enhancements-on-insertion-sort">Enhancements on insertion sort</h2><h3 id="method-1"><a href="https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.278.6654&amp;rep=rep1&amp;type=pdf">Method 1:</a></h3><p>Algorithm:</p><ol><li>Just compare the <em>ith</em> element with <em>(i-1)th</em> element.</li><li>If <em>ith</em> &gt; <em>(i-1)th</em>, then simply append the element to the list. Else</li><li>Compare <em>ith</em> element with ptr (i.e., the first element that is smallest in the current sorted list). We know that A[0] to A[i-1] is already sorted, and ptr points to A[0].</li><li>If <em>ith</em> &lt; ptr, then insert the <em>ith</em> element before ptr and point ptr to this element. Swap the remaining list accordingly. Else</li><li>If the element lies between the 1st and the <em>(i-1)th</em> element, then we further divide the total number of sorted elements by 2 i.e. k = ceil(i/2).</li><li>Now compare the <em>ith</em> element with the <em>kth</em> element and check again.</li><li>If <em>ith</em> &lt; <em>kth</em>, then continue comparing with smaller elements until we find an element <em>kth</em> &lt; <em>ith</em>. Compare <em>ith </em>element<em> </em>with <em>(k+1)th</em> and swap.</li><li>If <em>ith</em> &gt; <em>kth</em> then continue comparing with greater elements until we find an element <em>kth</em> &gt; <em>ith</em>. Compare <em>ith </em>element<em> </em>with (<em>k-1)th</em> and swap.</li></ol><p>Using this method, the average and worst-case complexity can be reduced to O(n^1.585) from O(n^2) as the number of comparisons reduces significantly. </p><h3 id="method-2"><a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.404.412&amp;rep=rep1&amp;type=pdf">Method 2:</a></h3><p>Algorithm:</p><ol><li>Start with the first and last elements of the array i.e. A[0] and A[n-1] where n is the length of the array.</li><li>Compare A[0] and A[n-1]. If A[0]&gt;A[n-1], swap their values. Else continue.</li><li>Compare A[1] and A[n-2] and swap if A[1] &gt; A[n-2].</li><li>Repeat this process until the two middle elements are processed or only one middle element remains.</li><li>Execute standard insertion sort on this array.</li></ol><p>This algorithm makes insertion sort more practical for larger list sizes by significantly reducing the number of comparisons. </p><hr><p>Congratulations! You have mastered insertion sort for your next big interview! If you haven&#x2019;t already, try implementing insertion sort yourself. Trust us! It is worth the effort :)</p><p>Sorting algorithms may seem dreary or complex at first glance. If this is the case with you, don&#x2019;t worry, we&#x2019;ve got your back! Check out our simple yet comprehensive summary of the <a href="https://www.crio.do/blog/top-10-sorting-algorithms/?utm_source=criodo-blog">Top 10 Sorting Algorithms</a>. </p><p>Happy Coding!</p><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure>]]></content:encoded></item><item><title><![CDATA[Master Insertion Sort Before Your Next Big Interview]]></title><description><![CDATA[Learn the details of insertion sort and how you can use it effectively to sort your dataset]]></description><link>https://www.crio.do/blog/insertion-sort/</link><guid isPermaLink="false">60e6a2963c06050ca13298bf</guid><category><![CDATA[Data Structures and Algorithms]]></category><dc:creator><![CDATA[Harshita Bansal]]></dc:creator><pubDate>Thu, 29 Sep 2022 05:51:00 GMT</pubDate><media:content url="https://www.crio.do/blog/content/images/2022/02/Insertion-Sort.png" medium="image"/><content:encoded><![CDATA[<img src="https://www.crio.do/blog/content/images/2022/02/Insertion-Sort.png" alt="Master Insertion Sort Before Your Next Big Interview"><p>Most programmers often feel the need to sort the data provided to them. Sorted data is easier to understand and process.</p><p>As resources become increasingly limited and time more valuable, the most efficient sorting mechanism must be implemented based on the characteristics of the data provided.</p><h3 id="various-types-of-sorting-mechanisms-include">Various types of sorting mechanisms include:</h3><ol><li><a href="https://www.crio.do/blog/quick-sort/?utm_source=criodo-blog">Quick Sort</a></li><li>Bubble Sort</li><li><a href="https://www.crio.do/blog/merge-sort-algorithm/?utm_source=criodo-blog">Merge Sort</a></li><li>Insertion Sort</li><li>Selection Sort</li><li>Heap Sort.</li><li>Radix Sort</li><li>Bucket Sort</li></ol><p>This blog covers the fundamentals to get you started with<strong> insertion sort</strong>. Before moving forward, make sure you have gone through the earlier blog on <a href="https://www.crio.do/blog/top-10-sorting-algorithms/?utm_source=criodo-blog">10 best sorting algorithms</a> to easily grasp the following sections.</p><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><h2 id="why-insertion-sort">Why insertion sort?</h2><p>Before diving into the technical details of insertion sort, consider this example:</p><p>You and your pet dog (let&#x2019;s call him Fluffy) are participating in a competition. <br>To win, Fluffy must run to a basket, pick a bone and give it to you, while you need to arrange them in increasing order of length, all of it as quickly as possible. <br>Suppose Fluffy takes 60 seconds to bring a bone, and you need 10 seconds to sort it into its proper position. One approach would be to wait for Fluffy to stack all the bones near you and then sort them. </p><p>For 10 bones, this approach takes (60+10)*10 = 700 seconds. </p><p>Another possible approach would be to sort each bone as it comes into its proper position. This approach takes 60*10 = 600 seconds. That is 1 min 40 sec lesser! Yay!</p><p>Insertion sort does the same. It places a new bone in its proper position in an already sorted array (or subarray, as we will see further). </p><p>Now replace the dog, bone, and yourself with a hard drive, data, and a CPU. While transferring data from a slow hard drive to a CPU, data transfer may take more time than data processing at the CPU. Hence, to avoid wastage of CPU cycles, it is good to keep sorting data alongside and add new data to the sorted data. </p><p>Now let us study the process of insertion sort in detail.</p><h2 id="what-is-insertion-sort">What is insertion sort?</h2><p>Insertion sort is a sorting method that works by shifting each element in the array one at a time. It iterates through the input elements, expanding the sorted array each time by comparing the current element to the sorted array&apos;s greatest value. </p><p>If the current element is greater, it remains in place and continues to the next element; otherwise, it locates the element&apos;s appropriate location in the sorted array and transfers it there.</p><p>Finally, it moves any elements in the sorted array that are greater than the current element one place forward.</p><h3 id="try-it-yourself">Try it yourself</h3><p>Insertion sort strongly resembles how we sort playing cards. To understand how, simply pick every subsequent card from a deck and place it in its proper position by comparing its value. </p><hr><p>Another real-world example of insertion sort is how tailors arrange shirts in a closet. They always keep them in sorted order of size so that they can insert new shirts into the proper spot very quickly by shifting existing shirts forward to make room for the new shirt.</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Insertion-sort-example.png" class="kg-image" alt="Master Insertion Sort Before Your Next Big Interview" loading="lazy" width="1920" height="1812" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Insertion-sort-example.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Insertion-sort-example.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/Insertion-sort-example.png 1600w, https://www.crio.do/blog/content/images/2022/02/Insertion-sort-example.png 1920w" sizes="(min-width: 720px) 720px"></figure><h2 id="insertion-sort-algorithm">Insertion sort algorithm</h2><p>Step 1: The first element is assumed to be already sorted</p><p>Step 2: Select the next element.</p><p>Step 3: Compare all elements in the sorted sublist with the element to be sorted.</p><p>Step 4: Shift all elements in the sorted sub-list that are greater than the value to be sorted.</p><p>Step 5: Fill in the value.</p><p>Step 6: Continue until the list is sorted.</p><h2 id="insertion-sort-pseudocode">Insertion sort pseudocode</h2><p>Assume that the first element is already sorted, and begin the iteration from index = 1 (in a zero-based array).<br></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/07/Screenshot-2021-07-08-at-12.41.04-PM.png" class="kg-image" alt="Master Insertion Sort Before Your Next Big Interview" loading="lazy" width="746" height="167" srcset="https://www.crio.do/blog/content/images/size/w600/2021/07/Screenshot-2021-07-08-at-12.41.04-PM.png 600w, https://www.crio.do/blog/content/images/2021/07/Screenshot-2021-07-08-at-12.41.04-PM.png 746w" sizes="(min-width: 720px) 720px"></figure><p>This algorithm can also be implemented recursively, such that the function calls itself, as follows:<br></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/07/Screenshot-2021-07-08-at-12.42.41-PM.png" class="kg-image" alt="Master Insertion Sort Before Your Next Big Interview" loading="lazy" width="746" height="167" srcset="https://www.crio.do/blog/content/images/size/w600/2021/07/Screenshot-2021-07-08-at-12.42.41-PM.png 600w, https://www.crio.do/blog/content/images/2021/07/Screenshot-2021-07-08-at-12.42.41-PM.png 746w" sizes="(min-width: 720px) 720px"></figure><p>Now that you know the algorithm and the pseudocode, try implementing insertion sort on your own. You may take help from the code snippets provided. Feel free to reach out to us in the comments below in case you get stuck.</p><h3 id="insertion-sort-in-c">Insertion sort in C<br></h3><figure class="kg-card kg-image-card"><img src="https://lh5.googleusercontent.com/XL3vqiocjCIAqy5GNkB3yNSSKqnz7sY4LI4WqDT80Xk16qkarj-q7JSQNxmDSyZmJVOs_AkZZjxo2u027_1xch8gmIQJ-yIlXI62z7GRGf5Vx9pkM8b0hUyrZtbeCrp6oobQbO5h" class="kg-image" alt="Master Insertion Sort Before Your Next Big Interview" loading="lazy"></figure><h3 id="insertion-sort-in-c-1">Insertion sort in C++<br></h3><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/M4OQnKGGhXIuXZ2NddgSyL8ZiC5NwL5Ky_esEbP73rFZABIHKp8qhYTtXdkUSTwR0BTkEWaKwAaIBejku_H5beUGHU1pqRh5FX-tuH9QvEzEsoMeoXgsj0PQ94nbko-ngziYaRn7" class="kg-image" alt="Master Insertion Sort Before Your Next Big Interview" loading="lazy"></figure><h3 id="insertion-sort-in-java">Insertion sort in Java<br></h3><figure class="kg-card kg-image-card"><img src="https://lh6.googleusercontent.com/dYiD9n1BleDWutMVjdVqHfJahAFNSDPr-X5kO-P9kyWK9lkcIDlOWWOwmLRmPlQdxKDfOrclWZ7E5VZU4lpgI0d_sMhiXwOhGe4mPPvtf8wakGY6bFBjZMcJPjBu3r12zdjes4Ri" class="kg-image" alt="Master Insertion Sort Before Your Next Big Interview" loading="lazy"></figure><h3 id="insertion-sort-in-python3">Insertion sort in Python3<br></h3><figure class="kg-card kg-image-card"><img src="https://lh3.googleusercontent.com/otketgf7fAFjC5foqDg_n9Sz7i_7XzvOmeFxLiImHa7KXQ3p5zDdpMC9_IW0-4jFh5TtGMeONKQugY1ulFZyfzlOv6ybxNFZHZbMCWSnAnZSLaW1-KR4S7WIX4JuNjvrH1cIi3qi" class="kg-image" alt="Master Insertion Sort Before Your Next Big Interview" loading="lazy"></figure><h2 id="time-complexity-analysis-of-insertion-sort">Time complexity analysis of insertion sort</h2><p>The <strong>best case</strong> input to an insertion sort function is an array sorted in the required order (here, ascending). In such cases, the algorithm simply compares the values of the <em>ith</em> element and the sorted subarray. Thus we get a linear time complexity, i.e., O(n). </p><p>The <strong>worst-case</strong> input is an array sorted in the opposite order (here, descending). In such cases, the algorithm compares the <em>ith</em> elements to every value in the sorted subarray and shifts every element of the subarray one position forward, thus resulting in quadratic time complexity, i.e., O(n2).</p><p>The<strong> average case</strong> complexity of insertion sort is also quadratic. Hence insertion sort is not preferred for large data sets. However, insertion sort is the fastest algorithm for sorting small arrays. Note that while there is no concrete threshold value to define small and large arrays, it may lie anywhere between 10 to 50 elements.</p><h2 id="space-complexity-analysis-of-insertion-sort">Space complexity analysis of insertion sort</h2><p>Space complexity is the same for all cases, i.e., O(1). Hence, no auxiliary memory is required.</p><h2 id="comparison-of-insertion-sort-with-other-sorting-algorithms">Comparison of insertion sort with other sorting algorithms</h2><p>Insertion sort is similar to selection sort; the primary difference is that the <em>ith</em> iteration in insertion sort gives the sorted subarray from the <em>i</em> elements input to it, whereas, in selection sort, the <em>ith</em> iteration gives the <em>i</em> smallest elements in the entire array. </p><p>Although bubble sort has the same time complexity, i.e., O(n2), it is far less efficient than both insertion and selection sort. While some divide-and-conquer algorithms, such as <a href="https://www.crio.do/blog/quick-sort/?utm_source=criodo-blog">Quick Sort</a> and <a href="https://www.crio.do/blog/merge-sort-algorithm/?utm_source=criodo-blog">Merge Sort</a>, outperform insertion sort for larger arrays, non-recursive sorting methods such as insertion sort or selection sort are often quicker for small arrays.</p><h2 id="enhancements-on-insertion-sort">Enhancements on insertion sort</h2><h3 id="method-1"><a href="https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.278.6654&amp;rep=rep1&amp;type=pdf">Method 1:</a></h3><p>Algorithm:</p><ol><li>Just compare the <em>ith</em> element with <em>(i-1)th</em> element.</li><li>If <em>ith</em> &gt; <em>(i-1)th</em>, then simply append the element to the list. Else</li><li>Compare <em>ith</em> element with ptr (i.e., the first element that is smallest in the current sorted list). We know that A[0] to A[i-1] is already sorted, and ptr points to A[0].</li><li>If <em>ith</em> &lt; ptr, then insert the <em>ith</em> element before ptr and point ptr to this element. Swap the remaining list accordingly. Else</li><li>If the element lies between the 1st and the <em>(i-1)th</em> element, then we further divide the total number of sorted elements by 2 i.e. k = ceil(i/2).</li><li>Now compare the <em>ith</em> element with the <em>kth</em> element and check again.</li><li>If <em>ith</em> &lt; <em>kth</em>, then continue comparing with smaller elements until we find an element <em>kth</em> &lt; <em>ith</em>. Compare <em>ith </em>element<em> </em>with <em>(k+1)th</em> and swap.</li><li>If <em>ith</em> &gt; <em>kth</em> then continue comparing with greater elements until we find an element <em>kth</em> &gt; <em>ith</em>. Compare <em>ith </em>element<em> </em>with (<em>k-1)th</em> and swap.</li></ol><p>Using this method, the average and worst-case complexity can be reduced to O(n^1.585) from O(n^2) as the number of comparisons reduces significantly. </p><h3 id="method-2"><a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.404.412&amp;rep=rep1&amp;type=pdf">Method 2:</a></h3><p>Algorithm:</p><ol><li>Start with the first and last elements of the array i.e. A[0] and A[n-1] where n is the length of the array.</li><li>Compare A[0] and A[n-1]. If A[0]&gt;A[n-1], swap their values. Else continue.</li><li>Compare A[1] and A[n-2] and swap if A[1] &gt; A[n-2].</li><li>Repeat this process until the two middle elements are processed or only one middle element remains.</li><li>Execute standard insertion sort on this array.</li></ol><p>This algorithm makes insertion sort more practical for larger list sizes by significantly reducing the number of comparisons. </p><hr><p>Congratulations! You have mastered insertion sort for your next big interview! If you haven&#x2019;t already, try implementing insertion sort yourself. Trust us! It is worth the effort :)</p><p>Sorting algorithms may seem dreary or complex at first glance. If this is the case with you, don&#x2019;t worry, we&#x2019;ve got your back! Check out our simple yet comprehensive summary of the <a href="https://www.crio.do/blog/top-10-sorting-algorithms/?utm_source=criodo-blog">Top 10 Sorting Algorithms</a>. </p><p>Happy Coding!</p><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure>]]></content:encoded></item><item><title><![CDATA[Time Complexity Examples - Simplified 10 Min Guide]]></title><description><![CDATA[O(1), O(n), O(n^2), O(log2 n), O (n log n), O(2^N), constant time complexity examples, Omega Notation, Ω, Theta Notation, Time Complexity Analysis]]></description><link>https://www.crio.do/blog/time-complexity-explained-2/</link><guid isPermaLink="false">66c783bc134c11095afa9305</guid><category><![CDATA[Data Structures and Algorithms]]></category><dc:creator><![CDATA[Sandipan Das]]></dc:creator><pubDate>Fri, 26 Aug 2022 08:47:00 GMT</pubDate><media:content url="https://www.crio.do/blog/content/images/2022/02/time-complexity-of-sorting-algorithms.png" medium="image"/><content:encoded><![CDATA[<h3 id="what-is-time-complexity">What is time complexity?</h3><img src="https://www.crio.do/blog/content/images/2022/02/time-complexity-of-sorting-algorithms.png" alt="Time Complexity Examples - Simplified 10 Min Guide"><p>Time complexity is a programming term that quantifies the amount of time it takes a sequence of code or an algorithm to process or execute in proportion to the size and cost of input.</p><p>It will not look at an algorithm&apos;s overall execution time. Rather, it will provide data on the variation (increase or reduction) in execution time when the number of operations in an algorithm increases or decreases. </p><p>Yes, as the definition suggests, the amount of time it takes is solely determined by the number of iterations of one-line statements inside the code.</p><p><strong>Take a look at this piece of code:</strong></p><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/JgI8EESVOdIg6HWlL1ObPmAW20o_g8nlRhYEQRGUyLpxUhUTr_kGEQSJjdx3XyF9LUBjr5lqcmjKUHkJlavAAFs892SO_8KvDNexyWjBLCupQ_rsLXRLNcLqUizdyQ" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p>Although there are three separate statements inside the <strong>main()</strong> function, the overall time complexity is still <strong>O(1)</strong> because each statement only takes unit time to complete execution.</p><p>Whereas, observe this example:</p><figure class="kg-card kg-image-card"><img src="https://lh5.googleusercontent.com/d5S9csCx6E8Omt8_oU6VAwySARDgrVt43F53FyK42Iw8pIx5TJNf1ow0fE8_ECMXDI3E4ZKhB0Y0WdJLagYra9Vd9j5r1MlCgsfrT8HK1gWG9u0qI9dcj_aQLnLsyQ" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p>Here, the <strong>O(1)</strong> chunk of code (the 3 cout statements) is enclosed inside a looping statement which <strong>repeats iteration for &apos;n&apos; number of times</strong>. Thus our overall time complexity becomes n*O(1), i.e., <strong>O(n)</strong>.</p><p>You could say that when an algorithm employs statements that are only executed once, the time required is constant. However, when the statement is in loop condition, the time required grows as the number of times the loop is set to run grows.</p><p>When an algorithm has a mix of single-executed statements and LOOP statements, or nested LOOP statements, the time required increases according to the number of times each statement is run.</p><p>For example, if a <strong>recursive function</strong> is called multiple times, identifying and recognizing the source of its time complexity may help reduce the overall processing time from <strong>600 ms</strong> to <strong>100 ms</strong>, for instance. That&apos;s what time complexity analysis aims to achieve.</p><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><h2 id="understanding-various-time-complexity-notations">Understanding various Time Complexity notations</h2><p>The following are some of the most common asymptotic notations for calculating an algorithm&apos;s running time complexity;</p><ul><li><strong>&#x39F; Notation</strong></li><li><strong>&#x3A9; Notation</strong></li><li><strong>&#x3B8; Notation</strong></li></ul><hr><p>Before you dig in, don&apos;t miss to check out the top 10 sorting algorithms used</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/top-10-sorting-algorithms/?utm_source=blog-int"><div class="kg-bookmark-content"><div class="kg-bookmark-title">10 Best Sorting Algorithms You Must To Know About</div><div class="kg-bookmark-description">What is the fastest sorting algorithm? Which one is the simplest sorting algorithm? Why do we even use sorting algorithms? Get all your answers.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="Time Complexity Examples - Simplified 10 Min Guide"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Sandipan Das</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/04/Sorting-Algorithms.png" alt="Time Complexity Examples - Simplified 10 Min Guide"></div></a></figure><hr><h3 id="big-oh-notation-%CE%BF">Big Oh Notation, &#x39F;</h3><p>The systematic way to express the upper limit of an algorithm&apos;s running time is to use the Big-O notation O(n). It calculates the worst-case time complexity, or the maximum time an algorithm will take to complete execution.</p><p>Also, do remember that this is the <strong>most commonly used notation</strong> for expressing the time complexity of different algorithms unless specified otherwise.</p><p><strong>Definition:</strong></p><p>Let g and f be functions that belong to the set of natural numbers (N). The function f is said to be O(g), if there is a constant c &gt; 0 and a natural number n0 such that:</p><pre><code>f (n) &#x2264; cg(n) for all n &gt;= n0</code></pre><h3 id="omega-notation-%CF%89">Omega Notation, &#x3A9;</h3><p>The systematic way to express the lower bound of an algorithm&apos;s running time is to use the notation <em>&#x3A9;</em>(n). It calculates the best-case time complexity, or the shortest time an algorithm will take to complete.</p><p><strong>Definition:</strong></p><pre><code>&#x3A9;(g(n)) ={ f(n): there exist positive constants c and n0 such that 0 &#x2264; cg(n) &#x2264; f(n) for all n &#x2265; n0 }</code></pre><p>The above expression can be defined as a function f(n) which belongs to the set &#x3A9;(g(n)) if and only if there exists a positive constant c (c &gt; 0) such that it is greater than c*g(n) for a sufficiently large value of n.</p><p>The minimum time required by an algorithm to complete its execution is given by &#x3A9;(g(n)).</p><h3 id="theta-notation-%CE%B8">Theta Notation, &#x398;</h3><p>The systematic way to express both the lower limit and upper bound of an algorithm&apos;s running time is to use the notation (n).</p><p><strong>Definition:</strong></p><pre><code>&#x398;(g(n)) = {f(n): there exist certain positive constants x1, x2 and n0  such that 0 &#x2264; x1g(n) &#x2264; f(n) &#x2264; x2g(n) for all n &#x2265; n0}</code></pre><h3 id="why-should-you-learn-about-the-time-complexity-of-algorithms">Why should you learn about the time complexity of algorithms?</h3><p>In computer programming, <strong>an algorithm is a finite set of well-defined instructions</strong> that are usually performed in a computer to solve a class of problems or perform a common operation.</p><p>According to the description, a sequence of specified instructions must be provided to the machine for it to execute an algorithm or perform a specific task. A particular series of instructions may be interpreted in any number of ways to perform the same purpose.</p><p>We have mentioned that the algorithm is to be run on a computer, which leads to the next step of varying the operating system, processor, hardware, and other factors that can affect how an algorithm is run.</p><p>Now that you know that a variety of variables will affect the outcome of an algorithm, it&apos;s important to know how effective those algorithms are at completing tasks. <strong>To determine this, you must assess an algorithm&apos;s Space and Time complexity.</strong></p><p><em>An algorithm&apos;s space complexity quantifies how much space or memory it takes to run as a function of the length of the input while an algorithm&apos;s time complexity measures how long it takes an algorithm to run as a function of the length of the input.</em></p><p>That&apos;s why it&apos;s so important to learn about the time and space complexity analysis of various <a href="https://www.crio.do/blog/top-10-sorting-algorithms/?utm_source=blog-int">algorithms</a>.</p><p>Let&apos;s explore each time complexity type with an example.</p><h3 id="1-o1">1. O(1)</h3><p><strong>Where an algorithm&apos;s execution time is not based on the input size n, it is said to have constant time complexity with order O (1).</strong></p><p>Whatever be the input size<strong> n</strong>, the runtime doesn&#x2019;t change. Here&apos;s an example:</p><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/PMBKnMp8l08v4pCRcHT3gubRZldT4RDYCMLibIUpUcWXURoURlym4aL6arjtnWXpaqq1urinnNGgwBstp3aTQsVcOIugz3d-oBOWvG27-f6onxQHPY7zUjyh_QUEPq-TyzyIYc0" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p>As you can see, the message <strong>&quot;Hello World!!&quot;</strong> is printed only once. So, regardless of the operating system or computer configuration you are using, the time complexity is constant: O(1), i.e. any time a constant amount of time is required to execute code.</p><h3 id="2-on">2. O(n)</h3><p><strong>When the running time of an algorithm increases linearly with the length of the input, it is assumed to have linear time complexity</strong>, i.e. when a function checks all of the values in an input data set (or needs to iterate once through every value in the input), it is said to have a Time complexity of order O (n). Consider the following scenario:</p><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/cPuMDA4JtDSQgwgsWXOEt-R0nUS9us3Tgv6X3gjazTAa3Zrt6bmPsWPQ2oSClPBd48IbvIfE_HXoz_CAxX-eS4qTnaXvI1pHwdjoFH38UlbxKW3M9_Pl9U8cIIAMuG_UQIbhq_o" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p><strong>Output:</strong></p><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/dTHMGye_pza0EWGNP9kKi7Oxds405wj4Gj1NETm7FM246M3FF9Nn0gsmt-0paGOulYZoCDFfpjRNpQIMeFjE46tqGf5JRA4rZQH9LeOhINOYwxAf-q5XACfNfmaasW_YChO71Dk" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p>Based on the above code, you can see that the number of times the statement <strong>&quot;Hello fellow Developer!!&quot;</strong> is displayed on the console is directly dependent on the size of the input variable &apos;n&apos;. </p><p>If one unit of time is used to represent run time, the above program can be run in n times the amount of time. As a result, the program scales linearly with the size of the input, and it has an order of O(n).</p><h3 id="3-on2">3. O(n^2)</h3><p><strong>When the running time of an algorithm increases non-linearly O(n^2) with the length of the input, it is said to have a non-linear time complexity.</strong></p><p>In general, nested loops fall into the O(n)*O(n) = O(n^2) time complexity order, where one loop takes O(n) and if the function includes loops inside loops, it takes O(n)*O(n) = O(n^2).</p><p>Similarly, if the function has &#x2018;m&apos; loops inside the O(n) loop, the order is given by O (n*m), which is referred to as polynomial time complexity function.</p><p>Consider the following program:</p><figure class="kg-card kg-image-card"><img src="https://lh3.googleusercontent.com/1_mmniICgXj89xB2hjE7LrVzk9zfT2wUCabIlQ2yC1xAEgpVAw7Op5k40-Hrsl9P4xPBD5AGGHx4NHMEhA3oRv_MQeGbzsDc-vHMDrzHuzlMVCFQfZsIVPUe4H6aiHhiLAWlXes" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p><strong>Output:</strong></p><figure class="kg-card kg-image-card"><img src="https://lh6.googleusercontent.com/ehLmn6fZV4h8AGTL8URCPtYwh-padu-Z54bBS6HpzjMMZvSMeJ5mvSwgJl224mK7oG-vbrvmDipju9h970lBAg1WH3wfMP6DFHPbFilmmiYuwhnP4TwL5KsM9WpxOI4ZGy8ZKCo" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p>As you can see, there are two nested for loops such that the inner loop&apos;s complete iteration repeats based on the value of the outer loop. This is the primary reason why you see <strong>&quot;Hello dev!!&quot; printed 6 times (3*2)</strong>. </p><p>This amounts to the cumulative time complexity of <strong>O(m*n)</strong> &#xA0;or <strong>O(n^2)</strong> if you assume that the value of m is equal to the value of n.</p><h3 id="4-olog2-n">4. O(log2 n)</h3><p>When an algorithm decreases the magnitude of the input data in each step, it is said to have a logarithmic time complexity. This means that the number of operations is not proportionate to the size of the input.</p><p><strong>O (log2 n)</strong> basically implies that time increases linearly while the value of <strong>&apos;n&apos;</strong> increases exponentially. So, if computing <strong>10 elements take 1 second</strong>, computing <strong>100 elements takes 2 seconds</strong>, <strong>1000 elements take 3 seconds</strong>, and so on.</p><p>When using divide and conquer algorithms, such as binary search, the time complexity is O(log n). </p><p>Another example is <a href="https://www.crio.do/blog/quick-sort/?utm_source=blog-int">quicksort</a>, in which we partition the array into two sections and find a pivot element in O(n) time each time. As a result, it is O(log2 n)</p><p>Binary trees and binary search functions are examples of algorithms having logarithmic time complexity. Here, the search for a particular value in an array is done by separating the array into two parts and starting the search in one of them. This guarantees that the action isn&apos;t performed on every data element.</p><p>Consider the following code snippet:</p><figure class="kg-card kg-image-card"><img src="https://lh3.googleusercontent.com/h8duzJctWLejD6hLg40n_hCHx4K3XEU2XoIZv9eHjN1TKYaGty_Czc8knGYKwGLTsMXmyCiWyztuiFXtmJdgviDnIybUzf8E00qQv4-wW6OkkeuKp-HrKu6xhhETFdF2oN-jZvg" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p>The above program is a demonstration of the binary search technique, a famous divide-and-conquer approach to searching in logarithmic time complexity.</p><h3 id="time-complexity-analysis">Time Complexity Analysis</h3><p>Let us assume that we have an array of length <strong>32</strong>. We&apos;ll be applying <strong>Binary Search</strong> to search for a random element in it. At each iteration, the array is halved.</p><!--kg-card-begin: markdown--><ul>
<li>Iteration 0:
<ul>
<li>Length of array = 32</li>
</ul>
</li>
<li>Iteration 1:
<ul>
<li>Length of array = 32/2 = 16</li>
</ul>
</li>
<li>Iteration 2:
<ul>
<li>Length of array = 32/2^2 = 8</li>
</ul>
</li>
<li>Iteration 3:
<ul>
<li>Length of array = 32/2^3 = 4</li>
</ul>
</li>
<li>Iteration 4:
<ul>
<li>Length of array = 32/2^4 = 2</li>
</ul>
</li>
<li>Iteration 5:
<ul>
<li>Length of array = 32/2^5 = 1</li>
</ul>
</li>
</ul>
<!--kg-card-end: markdown--><p>Another example would be that for an array of size <strong>1024</strong>, only <strong>10</strong> iterations are needed to approach unity. For an array size of <strong>32768</strong>, we&apos;ll need only 15 iterations. Thus we can see that the number of operations grows at a very small rate compared to the size of the input array while complexity is logarithmic.</p><p><strong>To generalize, after k iterations, our array size approaches 1.</strong></p><p>Hence, n/2^k = 1 =&gt; n = 2^k</p><p>Applying logarithmic function on both sides, we get<br>=&gt; log2 (n) = log2 (2^k) =&gt; log2 (n) = k log2 (2)<br>or, =&gt; k = log2 (n)<br>Hence, the time complexity of Binary Search becomes <em><strong>log2(n), or O(log n)</strong></em></p><h3 id="5-o-n-log-n">5. O (n log n)</h3><p><strong>This time complexity is popularly known as linearithmic time complexity.</strong> It performs slightly slower as compared to linear time complexity but is still significantly better than the quadratic algorithm.</p><p>Consider the program snippet given below:</p><figure class="kg-card kg-image-card"><img src="https://lh3.googleusercontent.com/xTX9wXA3DuHMUeMw5iOAammaHMjlT5VvQ7uyToXbXekF1dy1oPYt6FKU56Wj45-chP0em8NRW21MD8577sfaKjrtNnjU4xF-uXWax8TkFbfDz3bu4FGFMWTl63r--NZ_d3OltRc" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p>The program above represents the <strong>merge sort algorithm</strong>.</p><p>Sorting arrays on separate computers take a significant time. Merge Sort algorithm is recursive and has a recurrence relation for time complexity as follows:</p><pre><code>T(n) = 2T(n/2) + &#x3B8;(n)</code></pre><p>The Recurrence Tree approach or the Master approach can be used to solve the aforementioned recurrence relation. </p><p>It belongs to Master Method Case II, and the recurrence answer is <strong>O(n*logn)</strong>. Since Merge Sort always partitions the array into two halves and merges the two halves in linear time, it has a time complexity of (n*logn) in all three circumstances (worst, average, and best).</p><p>Also, remember this, when it comes to <a href="https://www.crio.do/blog/top-10-sorting-algorithms/?utm_source=blog-int">sorting algorithms,</a> <strong>O(n*logn)</strong> is probably the best time complexity we can achieve.</p><h3 id="6-o2n">6. O(2^N)</h3><p><strong>An algorithm with exponential time complexity doubles in magnitude with each increment to the input data set.</strong> If you&apos;re familiar with other exponential growth patterns, this one works similarly. The time complexity begins with a modest level of difficulty and gradually increases till the end.</p><p>The <strong>Fibonacci series</strong> is a great way to demonstrate exponential time complexity. Given below is a code snippet that calculates and returns the nth Fibonacci number:</p><figure class="kg-card kg-image-card"><img src="https://lh5.googleusercontent.com/5rBclSQpcD0-YDpKpmaHJCkKYjk7GVTqvmPvSP9PCMhpqAxDL39mGNyiJ2lXthcFj-MDYAqjwTAua54qL0qHUjzWg4Np6doW8DDA_QRYDgTkq7WUkGdjhM_QVxjVa5zmY-WMpZU" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p><strong>Time Complexity Analysis:</strong></p><p>The recurrence relation for the above code snippet is:</p><pre><code>T(n) = T(n-1) + T(n-2)</code></pre><p>Using the recurrence tree method, you can easily deduce that this code does a lot of redundant calculations as shown below.</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Time-complexity-analysis-1.png" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy" width="2000" height="1111" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Time-complexity-analysis-1.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Time-complexity-analysis-1.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/Time-complexity-analysis-1.png 1600w, https://www.crio.do/blog/content/images/2022/02/Time-complexity-analysis-1.png 2212w" sizes="(min-width: 720px) 720px"></figure><p>Thus the time complexity of the Fibonacci series becomes exponential owing to these repetitive calculations.</p><p>Let&apos;s take an example here to drive home the magnitude of this time complexity.</p><p><strong>For n=3</strong>, it takes <strong>8 </strong>operations to calculate the 8th Fibonacci number.</p><p><strong>For n=4</strong>, it takes 16 operations</p><p>.</p><p>.</p><p><strong>For n=10</strong>, it takes <strong>1024 </strong>operations to reach the 10th Fibonacci number.</p><p>.</p><p>.</p><p>Now if we bump it up to <strong>100 (n=100)</strong>, we literally exceed <strong>billions and billions of calculations</strong> just to reach the 100th Fibonacci number.</p><p>That&apos;s scary right. That&apos;s why exponential time complexity is one of the worst time complexities out there.</p><p></p><p><strong>Now that you&apos;ve explored the major time complexities in algorithms and data structures, take a look at their graphical representation below: (Time vs Input Size)</strong></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/BIG-O-COMPLEXITY.png" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy" width="2000" height="1288" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/BIG-O-COMPLEXITY.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/BIG-O-COMPLEXITY.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/BIG-O-COMPLEXITY.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/02/BIG-O-COMPLEXITY.png 2400w" sizes="(min-width: 720px) 720px"></figure><p>Here&apos;s a simple comparison between different time complexities to help you understand the graph better:</p><pre><code>O(1) &lt; O(log2n) &lt; O(n1/2) &lt; O(n) &lt; O(n logn) &lt; O(n^2) &lt; O(n^3) &lt; . . . . &lt; O(2^n) &lt; O(3^n) &lt; . . . .  &lt; O(n^n)</code></pre><p>Of course, a visual representation clarifies a lot of concepts particularly related to the efficiency of different time complexities. </p><p><strong>The noticeable thing to observe is how inefficient exponential and quadratic time complexities are with increasing input data size.</strong></p><p>On the other hand, linearithmic and linear time complexities perform almost in a similar fashion with increasing input size.</p><p><strong>The astounding part is the performance of logarithmic time complexity which clearly supersedes most algorithmic time complexities (except O(1)) in terms of execution time and efficiency.</strong></p><h3 id="top-5-sorting-algorithms-and-their-time-complexities">Top 5 Sorting Algorithms and their time complexities</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Time-complexity-of-top-5-sorting-algorithms.png" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy" width="2000" height="1288" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Time-complexity-of-top-5-sorting-algorithms.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Time-complexity-of-top-5-sorting-algorithms.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/Time-complexity-of-top-5-sorting-algorithms.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/02/Time-complexity-of-top-5-sorting-algorithms.png 2400w" sizes="(min-width: 720px) 720px"></figure><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/top-10-sorting-algorithms/?utm_source=blog-int"><div class="kg-bookmark-content"><div class="kg-bookmark-title">10 Best Sorting Algorithms You Must To Know About</div><div class="kg-bookmark-description">What is the fastest sorting algorithm? Which one is the simplest sorting algorithm? Why do we even use sorting algorithms? Get all your answers.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="Time Complexity Examples - Simplified 10 Min Guide"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Sandipan Das</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/04/Sorting-Algorithms.png" alt="Time Complexity Examples - Simplified 10 Min Guide"></div></a></figure><hr><p><strong>HEY</strong>, seems like you just completed learning about one of the most important concepts in <a href="https://www.crio.do/blog/tag/data-structures-and-algorithms/?utm_source=blog-int">Data Structures and Algorithms</a>, i.e, <strong>time complexity analysis</strong>. Hope you enjoyed this <em><strong>code-based </strong></em>approach to such an interesting topic.</p><p><strong>With DSA it becomes important to identify the Time Complexity of a given piece of code in the long run.</strong></p><p>You can always jumpstart with the knowledge here and put it into practice analyzing various code snippets to up your <strong>Time Complexity</strong> game.</p><p>Of course, it will take time, but the experience you&apos;ll gain out of that will be more potent than just skimming through this article. So, what are you waiting for? Go ahead and crunch out some awesome problems for yourself.</p><p><em>Any particular time complexity that we missed out on? Let us know in the comments below.</em></p><p><em>Also, if you learned something new at any point in this article, please spread the knowledge by sharing it with your friends or with someone who might need it. </em></p><p><strong>HAPPY CODING!!</strong></p><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><p></p><p><br></p>]]></content:encoded></item><item><title><![CDATA[Time Complexity Examples - Simplified 10 Min Guide]]></title><description><![CDATA[O(1), O(n), O(n^2), O(log2 n), O (n log n), O(2^N), constant time complexity examples, Omega Notation, Ω, Theta Notation, Time Complexity Analysis]]></description><link>https://www.crio.do/blog/time-complexity-explained/</link><guid isPermaLink="false">60e43b593c06050ca132965c</guid><category><![CDATA[Data Structures and Algorithms]]></category><dc:creator><![CDATA[Sandipan Das]]></dc:creator><pubDate>Fri, 26 Aug 2022 08:47:00 GMT</pubDate><media:content url="https://www.crio.do/blog/content/images/2022/02/time-complexity-of-sorting-algorithms.png" medium="image"/><content:encoded><![CDATA[<h3 id="what-is-time-complexity">What is time complexity?</h3><img src="https://www.crio.do/blog/content/images/2022/02/time-complexity-of-sorting-algorithms.png" alt="Time Complexity Examples - Simplified 10 Min Guide"><p>Time complexity is a programming term that quantifies the amount of time it takes a sequence of code or an algorithm to process or execute in proportion to the size and cost of input.</p><p>It will not look at an algorithm&apos;s overall execution time. Rather, it will provide data on the variation (increase or reduction) in execution time when the number of operations in an algorithm increases or decreases. </p><p>Yes, as the definition suggests, the amount of time it takes is solely determined by the number of iterations of one-line statements inside the code.</p><p><strong>Take a look at this piece of code:</strong></p><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/JgI8EESVOdIg6HWlL1ObPmAW20o_g8nlRhYEQRGUyLpxUhUTr_kGEQSJjdx3XyF9LUBjr5lqcmjKUHkJlavAAFs892SO_8KvDNexyWjBLCupQ_rsLXRLNcLqUizdyQ" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p>Although there are three separate statements inside the <strong>main()</strong> function, the overall time complexity is still <strong>O(1)</strong> because each statement only takes unit time to complete execution.</p><p>Whereas, observe this example:</p><figure class="kg-card kg-image-card"><img src="https://lh5.googleusercontent.com/d5S9csCx6E8Omt8_oU6VAwySARDgrVt43F53FyK42Iw8pIx5TJNf1ow0fE8_ECMXDI3E4ZKhB0Y0WdJLagYra9Vd9j5r1MlCgsfrT8HK1gWG9u0qI9dcj_aQLnLsyQ" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p>Here, the <strong>O(1)</strong> chunk of code (the 3 cout statements) is enclosed inside a looping statement which <strong>repeats iteration for &apos;n&apos; number of times</strong>. Thus our overall time complexity becomes n*O(1), i.e., <strong>O(n)</strong>.</p><p>You could say that when an algorithm employs statements that are only executed once, the time required is constant. However, when the statement is in loop condition, the time required grows as the number of times the loop is set to run grows.</p><p>When an algorithm has a mix of single-executed statements and LOOP statements, or nested LOOP statements, the time required increases according to the number of times each statement is run.</p><p>For example, if a <strong>recursive function</strong> is called multiple times, identifying and recognizing the source of its time complexity may help reduce the overall processing time from <strong>600 ms</strong> to <strong>100 ms</strong>, for instance. That&apos;s what time complexity analysis aims to achieve.</p><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><h2 id="understanding-various-time-complexity-notations">Understanding various Time Complexity notations</h2><p>The following are some of the most common asymptotic notations for calculating an algorithm&apos;s running time complexity;</p><ul><li><strong>&#x39F; Notation</strong></li><li><strong>&#x3A9; Notation</strong></li><li><strong>&#x3B8; Notation</strong></li></ul><hr><p>Before you dig in, don&apos;t miss to check out the top 10 sorting algorithms used</p><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/top-10-sorting-algorithms/?utm_source=blog-int"><div class="kg-bookmark-content"><div class="kg-bookmark-title">10 Best Sorting Algorithms You Must To Know About</div><div class="kg-bookmark-description">What is the fastest sorting algorithm? Which one is the simplest sorting algorithm? Why do we even use sorting algorithms? Get all your answers.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="Time Complexity Examples - Simplified 10 Min Guide"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Sandipan Das</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/04/Sorting-Algorithms.png" alt="Time Complexity Examples - Simplified 10 Min Guide"></div></a></figure><hr><h3 id="big-oh-notation-%CE%BF">Big Oh Notation, &#x39F;</h3><p>The systematic way to express the upper limit of an algorithm&apos;s running time is to use the Big-O notation O(n). It calculates the worst-case time complexity, or the maximum time an algorithm will take to complete execution.</p><p>Also, do remember that this is the <strong>most commonly used notation</strong> for expressing the time complexity of different algorithms unless specified otherwise.</p><p><strong>Definition:</strong></p><p>Let g and f be functions that belong to the set of natural numbers (N). The function f is said to be O(g), if there is a constant c &gt; 0 and a natural number n0 such that:</p><pre><code>f (n) &#x2264; cg(n) for all n &gt;= n0</code></pre><h3 id="omega-notation-%CF%89">Omega Notation, &#x3A9;</h3><p>The systematic way to express the lower bound of an algorithm&apos;s running time is to use the notation <em>&#x3A9;</em>(n). It calculates the best-case time complexity, or the shortest time an algorithm will take to complete.</p><p><strong>Definition:</strong></p><pre><code>&#x3A9;(g(n)) ={ f(n): there exist positive constants c and n0 such that 0 &#x2264; cg(n) &#x2264; f(n) for all n &#x2265; n0 }</code></pre><p>The above expression can be defined as a function f(n) which belongs to the set &#x3A9;(g(n)) if and only if there exists a positive constant c (c &gt; 0) such that it is greater than c*g(n) for a sufficiently large value of n.</p><p>The minimum time required by an algorithm to complete its execution is given by &#x3A9;(g(n)).</p><h3 id="theta-notation-%CE%B8">Theta Notation, &#x398;</h3><p>The systematic way to express both the lower limit and upper bound of an algorithm&apos;s running time is to use the notation (n).</p><p><strong>Definition:</strong></p><pre><code>&#x398;(g(n)) = {f(n): there exist certain positive constants x1, x2 and n0  such that 0 &#x2264; x1g(n) &#x2264; f(n) &#x2264; x2g(n) for all n &#x2265; n0}</code></pre><h3 id="why-should-you-learn-about-the-time-complexity-of-algorithms">Why should you learn about the time complexity of algorithms?</h3><p>In computer programming, <strong>an algorithm is a finite set of well-defined instructions</strong> that are usually performed in a computer to solve a class of problems or perform a common operation.</p><p>According to the description, a sequence of specified instructions must be provided to the machine for it to execute an algorithm or perform a specific task. A particular series of instructions may be interpreted in any number of ways to perform the same purpose.</p><p>We have mentioned that the algorithm is to be run on a computer, which leads to the next step of varying the operating system, processor, hardware, and other factors that can affect how an algorithm is run.</p><p>Now that you know that a variety of variables will affect the outcome of an algorithm, it&apos;s important to know how effective those algorithms are at completing tasks. <strong>To determine this, you must assess an algorithm&apos;s Space and Time complexity.</strong></p><p><em>An algorithm&apos;s space complexity quantifies how much space or memory it takes to run as a function of the length of the input while an algorithm&apos;s time complexity measures how long it takes an algorithm to run as a function of the length of the input.</em></p><p>That&apos;s why it&apos;s so important to learn about the time and space complexity analysis of various <a href="https://www.crio.do/blog/top-10-sorting-algorithms/?utm_source=blog-int">algorithms</a>.</p><p>Let&apos;s explore each time complexity type with an example.</p><h3 id="1-o1">1. O(1)</h3><p><strong>Where an algorithm&apos;s execution time is not based on the input size n, it is said to have constant time complexity with order O (1).</strong></p><p>Whatever be the input size<strong> n</strong>, the runtime doesn&#x2019;t change. Here&apos;s an example:</p><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/PMBKnMp8l08v4pCRcHT3gubRZldT4RDYCMLibIUpUcWXURoURlym4aL6arjtnWXpaqq1urinnNGgwBstp3aTQsVcOIugz3d-oBOWvG27-f6onxQHPY7zUjyh_QUEPq-TyzyIYc0" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p>As you can see, the message <strong>&quot;Hello World!!&quot;</strong> is printed only once. So, regardless of the operating system or computer configuration you are using, the time complexity is constant: O(1), i.e. any time a constant amount of time is required to execute code.</p><h3 id="2-on">2. O(n)</h3><p><strong>When the running time of an algorithm increases linearly with the length of the input, it is assumed to have linear time complexity</strong>, i.e. when a function checks all of the values in an input data set (or needs to iterate once through every value in the input), it is said to have a Time complexity of order O (n). Consider the following scenario:</p><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/cPuMDA4JtDSQgwgsWXOEt-R0nUS9us3Tgv6X3gjazTAa3Zrt6bmPsWPQ2oSClPBd48IbvIfE_HXoz_CAxX-eS4qTnaXvI1pHwdjoFH38UlbxKW3M9_Pl9U8cIIAMuG_UQIbhq_o" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p><strong>Output:</strong></p><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/dTHMGye_pza0EWGNP9kKi7Oxds405wj4Gj1NETm7FM246M3FF9Nn0gsmt-0paGOulYZoCDFfpjRNpQIMeFjE46tqGf5JRA4rZQH9LeOhINOYwxAf-q5XACfNfmaasW_YChO71Dk" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p>Based on the above code, you can see that the number of times the statement <strong>&quot;Hello fellow Developer!!&quot;</strong> is displayed on the console is directly dependent on the size of the input variable &apos;n&apos;. </p><p>If one unit of time is used to represent run time, the above program can be run in n times the amount of time. As a result, the program scales linearly with the size of the input, and it has an order of O(n).</p><h3 id="3-on2">3. O(n^2)</h3><p><strong>When the running time of an algorithm increases non-linearly O(n^2) with the length of the input, it is said to have a non-linear time complexity.</strong></p><p>In general, nested loops fall into the O(n)*O(n) = O(n^2) time complexity order, where one loop takes O(n) and if the function includes loops inside loops, it takes O(n)*O(n) = O(n^2).</p><p>Similarly, if the function has &#x2018;m&apos; loops inside the O(n) loop, the order is given by O (n*m), which is referred to as polynomial time complexity function.</p><p>Consider the following program:</p><figure class="kg-card kg-image-card"><img src="https://lh3.googleusercontent.com/1_mmniICgXj89xB2hjE7LrVzk9zfT2wUCabIlQ2yC1xAEgpVAw7Op5k40-Hrsl9P4xPBD5AGGHx4NHMEhA3oRv_MQeGbzsDc-vHMDrzHuzlMVCFQfZsIVPUe4H6aiHhiLAWlXes" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p><strong>Output:</strong></p><figure class="kg-card kg-image-card"><img src="https://lh6.googleusercontent.com/ehLmn6fZV4h8AGTL8URCPtYwh-padu-Z54bBS6HpzjMMZvSMeJ5mvSwgJl224mK7oG-vbrvmDipju9h970lBAg1WH3wfMP6DFHPbFilmmiYuwhnP4TwL5KsM9WpxOI4ZGy8ZKCo" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p>As you can see, there are two nested for loops such that the inner loop&apos;s complete iteration repeats based on the value of the outer loop. This is the primary reason why you see <strong>&quot;Hello dev!!&quot; printed 6 times (3*2)</strong>. </p><p>This amounts to the cumulative time complexity of <strong>O(m*n)</strong> &#xA0;or <strong>O(n^2)</strong> if you assume that the value of m is equal to the value of n.</p><h3 id="4-olog2-n">4. O(log2 n)</h3><p>When an algorithm decreases the magnitude of the input data in each step, it is said to have a logarithmic time complexity. This means that the number of operations is not proportionate to the size of the input.</p><p><strong>O (log2 n)</strong> basically implies that time increases linearly while the value of <strong>&apos;n&apos;</strong> increases exponentially. So, if computing <strong>10 elements take 1 second</strong>, computing <strong>100 elements takes 2 seconds</strong>, <strong>1000 elements take 3 seconds</strong>, and so on.</p><p>When using divide and conquer algorithms, such as binary search, the time complexity is O(log n). </p><p>Another example is <a href="https://www.crio.do/blog/quick-sort/?utm_source=blog-int">quicksort</a>, in which we partition the array into two sections and find a pivot element in O(n) time each time. As a result, it is O(log2 n)</p><p>Binary trees and binary search functions are examples of algorithms having logarithmic time complexity. Here, the search for a particular value in an array is done by separating the array into two parts and starting the search in one of them. This guarantees that the action isn&apos;t performed on every data element.</p><p>Consider the following code snippet:</p><figure class="kg-card kg-image-card"><img src="https://lh3.googleusercontent.com/h8duzJctWLejD6hLg40n_hCHx4K3XEU2XoIZv9eHjN1TKYaGty_Czc8knGYKwGLTsMXmyCiWyztuiFXtmJdgviDnIybUzf8E00qQv4-wW6OkkeuKp-HrKu6xhhETFdF2oN-jZvg" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p>The above program is a demonstration of the binary search technique, a famous divide-and-conquer approach to searching in logarithmic time complexity.</p><h3 id="time-complexity-analysis">Time Complexity Analysis</h3><p>Let us assume that we have an array of length <strong>32</strong>. We&apos;ll be applying <strong>Binary Search</strong> to search for a random element in it. At each iteration, the array is halved.</p><!--kg-card-begin: markdown--><ul>
<li>Iteration 0:
<ul>
<li>Length of array = 32</li>
</ul>
</li>
<li>Iteration 1:
<ul>
<li>Length of array = 32/2 = 16</li>
</ul>
</li>
<li>Iteration 2:
<ul>
<li>Length of array = 32/2^2 = 8</li>
</ul>
</li>
<li>Iteration 3:
<ul>
<li>Length of array = 32/2^3 = 4</li>
</ul>
</li>
<li>Iteration 4:
<ul>
<li>Length of array = 32/2^4 = 2</li>
</ul>
</li>
<li>Iteration 5:
<ul>
<li>Length of array = 32/2^5 = 1</li>
</ul>
</li>
</ul>
<!--kg-card-end: markdown--><p>Another example would be that for an array of size <strong>1024</strong>, only <strong>10</strong> iterations are needed to approach unity. For an array size of <strong>32768</strong>, we&apos;ll need only 15 iterations. Thus we can see that the number of operations grows at a very small rate compared to the size of the input array while complexity is logarithmic.</p><p><strong>To generalize, after k iterations, our array size approaches 1.</strong></p><p>Hence, n/2^k = 1 =&gt; n = 2^k</p><p>Applying logarithmic function on both sides, we get<br>=&gt; log2 (n) = log2 (2^k) =&gt; log2 (n) = k log2 (2)<br>or, =&gt; k = log2 (n)<br>Hence, the time complexity of Binary Search becomes <em><strong>log2(n), or O(log n)</strong></em></p><h3 id="5-o-n-log-n">5. O (n log n)</h3><p><strong>This time complexity is popularly known as linearithmic time complexity.</strong> It performs slightly slower as compared to linear time complexity but is still significantly better than the quadratic algorithm.</p><p>Consider the program snippet given below:</p><figure class="kg-card kg-image-card"><img src="https://lh3.googleusercontent.com/xTX9wXA3DuHMUeMw5iOAammaHMjlT5VvQ7uyToXbXekF1dy1oPYt6FKU56Wj45-chP0em8NRW21MD8577sfaKjrtNnjU4xF-uXWax8TkFbfDz3bu4FGFMWTl63r--NZ_d3OltRc" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p>The program above represents the <strong>merge sort algorithm</strong>.</p><p>Sorting arrays on separate computers take a significant time. Merge Sort algorithm is recursive and has a recurrence relation for time complexity as follows:</p><pre><code>T(n) = 2T(n/2) + &#x3B8;(n)</code></pre><p>The Recurrence Tree approach or the Master approach can be used to solve the aforementioned recurrence relation. </p><p>It belongs to Master Method Case II, and the recurrence answer is <strong>O(n*logn)</strong>. Since Merge Sort always partitions the array into two halves and merges the two halves in linear time, it has a time complexity of (n*logn) in all three circumstances (worst, average, and best).</p><p>Also, remember this, when it comes to <a href="https://www.crio.do/blog/top-10-sorting-algorithms/?utm_source=blog-int">sorting algorithms,</a> <strong>O(n*logn)</strong> is probably the best time complexity we can achieve.</p><h3 id="6-o2n">6. O(2^N)</h3><p><strong>An algorithm with exponential time complexity doubles in magnitude with each increment to the input data set.</strong> If you&apos;re familiar with other exponential growth patterns, this one works similarly. The time complexity begins with a modest level of difficulty and gradually increases till the end.</p><p>The <strong>Fibonacci series</strong> is a great way to demonstrate exponential time complexity. Given below is a code snippet that calculates and returns the nth Fibonacci number:</p><figure class="kg-card kg-image-card"><img src="https://lh5.googleusercontent.com/5rBclSQpcD0-YDpKpmaHJCkKYjk7GVTqvmPvSP9PCMhpqAxDL39mGNyiJ2lXthcFj-MDYAqjwTAua54qL0qHUjzWg4Np6doW8DDA_QRYDgTkq7WUkGdjhM_QVxjVa5zmY-WMpZU" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy"></figure><p><strong>Time Complexity Analysis:</strong></p><p>The recurrence relation for the above code snippet is:</p><pre><code>T(n) = T(n-1) + T(n-2)</code></pre><p>Using the recurrence tree method, you can easily deduce that this code does a lot of redundant calculations as shown below.</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Time-complexity-analysis-1.png" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy" width="2000" height="1111" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Time-complexity-analysis-1.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Time-complexity-analysis-1.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/Time-complexity-analysis-1.png 1600w, https://www.crio.do/blog/content/images/2022/02/Time-complexity-analysis-1.png 2212w" sizes="(min-width: 720px) 720px"></figure><p>Thus the time complexity of the Fibonacci series becomes exponential owing to these repetitive calculations.</p><p>Let&apos;s take an example here to drive home the magnitude of this time complexity.</p><p><strong>For n=3</strong>, it takes <strong>8 </strong>operations to calculate the 8th Fibonacci number.</p><p><strong>For n=4</strong>, it takes 16 operations</p><p>.</p><p>.</p><p><strong>For n=10</strong>, it takes <strong>1024 </strong>operations to reach the 10th Fibonacci number.</p><p>.</p><p>.</p><p>Now if we bump it up to <strong>100 (n=100)</strong>, we literally exceed <strong>billions and billions of calculations</strong> just to reach the 100th Fibonacci number.</p><p>That&apos;s scary right. That&apos;s why exponential time complexity is one of the worst time complexities out there.</p><p></p><p><strong>Now that you&apos;ve explored the major time complexities in algorithms and data structures, take a look at their graphical representation below: (Time vs Input Size)</strong></p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/BIG-O-COMPLEXITY.png" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy" width="2000" height="1288" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/BIG-O-COMPLEXITY.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/BIG-O-COMPLEXITY.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/BIG-O-COMPLEXITY.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/02/BIG-O-COMPLEXITY.png 2400w" sizes="(min-width: 720px) 720px"></figure><p>Here&apos;s a simple comparison between different time complexities to help you understand the graph better:</p><pre><code>O(1) &lt; O(log2n) &lt; O(n1/2) &lt; O(n) &lt; O(n logn) &lt; O(n^2) &lt; O(n^3) &lt; . . . . &lt; O(2^n) &lt; O(3^n) &lt; . . . .  &lt; O(n^n)</code></pre><p>Of course, a visual representation clarifies a lot of concepts particularly related to the efficiency of different time complexities. </p><p><strong>The noticeable thing to observe is how inefficient exponential and quadratic time complexities are with increasing input data size.</strong></p><p>On the other hand, linearithmic and linear time complexities perform almost in a similar fashion with increasing input size.</p><p><strong>The astounding part is the performance of logarithmic time complexity which clearly supersedes most algorithmic time complexities (except O(1)) in terms of execution time and efficiency.</strong></p><h3 id="top-5-sorting-algorithms-and-their-time-complexities">Top 5 Sorting Algorithms and their time complexities</h3><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Time-complexity-of-top-5-sorting-algorithms.png" class="kg-image" alt="Time Complexity Examples - Simplified 10 Min Guide" loading="lazy" width="2000" height="1288" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Time-complexity-of-top-5-sorting-algorithms.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Time-complexity-of-top-5-sorting-algorithms.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/Time-complexity-of-top-5-sorting-algorithms.png 1600w, https://www.crio.do/blog/content/images/size/w2400/2022/02/Time-complexity-of-top-5-sorting-algorithms.png 2400w" sizes="(min-width: 720px) 720px"></figure><figure class="kg-card kg-bookmark-card"><a class="kg-bookmark-container" href="https://www.crio.do/blog/top-10-sorting-algorithms/?utm_source=blog-int"><div class="kg-bookmark-content"><div class="kg-bookmark-title">10 Best Sorting Algorithms You Must To Know About</div><div class="kg-bookmark-description">What is the fastest sorting algorithm? Which one is the simplest sorting algorithm? Why do we even use sorting algorithms? Get all your answers.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://www.crio.do/blog/favicon.ico" alt="Time Complexity Examples - Simplified 10 Min Guide"><span class="kg-bookmark-author">Crio Blog</span><span class="kg-bookmark-publisher">Sandipan Das</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://www.crio.do/blog/content/images/2021/04/Sorting-Algorithms.png" alt="Time Complexity Examples - Simplified 10 Min Guide"></div></a></figure><hr><p><strong>HEY</strong>, seems like you just completed learning about one of the most important concepts in <a href="https://www.crio.do/blog/tag/data-structures-and-algorithms/?utm_source=blog-int">Data Structures and Algorithms</a>, i.e, <strong>time complexity analysis</strong>. Hope you enjoyed this <em><strong>code-based </strong></em>approach to such an interesting topic.</p><p><strong>With DSA it becomes important to identify the Time Complexity of a given piece of code in the long run.</strong></p><p>You can always jumpstart with the knowledge here and put it into practice analyzing various code snippets to up your <strong>Time Complexity</strong> game.</p><p>Of course, it will take time, but the experience you&apos;ll gain out of that will be more potent than just skimming through this article. So, what are you waiting for? Go ahead and crunch out some awesome problems for yourself.</p><p><em>Any particular time complexity that we missed out on? Let us know in the comments below.</em></p><p><em>Also, if you learned something new at any point in this article, please spread the knowledge by sharing it with your friends or with someone who might need it. </em></p><p><strong>HAPPY CODING!!</strong></p><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><p></p><p><br></p>]]></content:encoded></item><item><title><![CDATA[Why Do Companies Ask DSA Questions in Interviews?]]></title><description><![CDATA[Most of the interviews for technical roles in product-based companies are focused on measuring the Data Structures and Algorithms knowledge of the candidates. But, why such emphasis on this topic? Read on to know more...]]></description><link>https://www.crio.do/blog/why-learn-data-structures-and-algorithms-2/</link><guid isPermaLink="false">66c783bc134c11095afa9329</guid><category><![CDATA[Career Guidance]]></category><category><![CDATA[Data Structures and Algorithms]]></category><dc:creator><![CDATA[Abheetha Pradhan]]></dc:creator><pubDate>Tue, 23 Aug 2022 13:26:00 GMT</pubDate><media:content url="https://www.crio.do/blog/content/images/2022/04/Why-do-companies-ask-DSA-questions.png" medium="image"/><content:encoded><![CDATA[<figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/ZUBoG6j-Vco?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><h2 id="what-is-dsa">What is DSA?</h2><img src="https://www.crio.do/blog/content/images/2022/04/Why-do-companies-ask-DSA-questions.png" alt="Why Do Companies Ask DSA Questions in Interviews?"><p>DSA stands for Data Structures and Algorithms. It is also sometimes referred to as PSDS - Problem Solving Data Structures. DSA is applied in problem-solving and enables developers to learn to write efficient code. The quality of the code can be judged by how much memory and time it consumes. The lesser memory the code consumes and the faster it runs, the more efficient it is.</p><h2 id="why-is-dsa-important">Why is DSA important?</h2><p>A person equipped with strong DSA skills will have better and more efficient approaches to solving a problem than someone who is not aware of DSA concepts. </p><p>You might not apply DSA directly in your job, but DSA is the foundation of computer science. You will certainly be a better software engineer if you have mastered DSA. So it&apos;s advisable to slowly master it at the beginning of your IT career itself.</p><h2 id="how-do-companies-use-dsa">How do companies use DSA?</h2><p>Companies use DSA in mainly two ways - </p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/04/How-do-companies-use-DSA.png" class="kg-image" alt="Why Do Companies Ask DSA Questions in Interviews?" loading="lazy" width="1920" height="687" srcset="https://www.crio.do/blog/content/images/size/w600/2022/04/How-do-companies-use-DSA.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/04/How-do-companies-use-DSA.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/04/How-do-companies-use-DSA.png 1600w, https://www.crio.do/blog/content/images/2022/04/How-do-companies-use-DSA.png 1920w" sizes="(min-width: 720px) 720px"></figure><p>In both of these cases, you as a candidate are required to write code to solve a problem that uses DSA.</p><p>Websites like HackerRank, LeetCode, and CodeForces have large sets of problems ranging from easy, medium, and hard levels of difficulty. Anybody can sign up on these websites and solve problems by writing code in any of the major programming languages and hone their skills in PSDS. </p><p>A lot of companies also use these websites to set interview questions. These websites have powerful evaluation tools to check your program for different test cases and also to test your program for plagiarism.</p><h3 id="1-online-screening">1. Online Screening</h3><p>Companies use DSA to filter candidates. A company could have as many as 500 applicants and they might need to shortlist 20 candidates. DSA coding assessments serve as an objective way to filter the candidates.</p><p>By doing this,</p><ol><li>The company spends &lt; 1-2 hors setting problems on HackerRank and get automated leaderboard performance results back from Hackerrank.</li><li>Candidates don&#x2019;t spend more than 2 hours of their time going to the next stage of the interview.<br></li></ol><p>Without doing this,</p><ol><li>The company asks all the 500 applicants to build a project for 12 hours</li><li>The company has to build automatic assessments for this project which is 20+ hours of work for their engineers</li><li>Candidates who get rejected have wasted 12 hours of their precious time. <br></li></ol><p><strong>How are coding assessments fair?</strong></p><ol><li>The coding ability of the candidates is judged.</li><li>Depth of DSA knowledge is judged based on the difficulty level of the problems set.<br></li></ol><p>But there are some disadvantages to this method of filtering candidates</p><p><strong>1. Plagiarism</strong></p><p>Anybody can take up the online test unless strict measures of proctoring are implemented. </p><p><strong>2. Problem Difficulty</strong></p><p>The difficulty of the problems is progressively raised with a larger number of candidates. This is because companies don&#x2019;t want all candidates to have the same score; they need a stack rank.</p><p>Because of this, online coding assessments can become too hard, more than what is required for the job.</p><h3 id="2-personal-interviews">2. Personal interviews</h3><p>Apart from coding ability &amp; DSA knowledge, the personal interview rounds aim at assessing a few more skills of the candidate:</p><p><strong>Problem-solving ability</strong></p><p>They evaluate if you are able to ask the right questions, come up with multiple solutions, are able to cover all aspects of the problem, make the right trade-offs, etc.</p><p><strong>Debugging ability</strong></p><p>The interviewer will also assess you by checking if you are able to structurally debug the code when you face issues.</p><p>In other terms, during online assessments, companies usually look for the final output of the code you have written. Whereas during personal interviews, the interviewer is interested in understanding your approach to solving the problem.</p><p>Well-prepared interviewers don&#x2019;t usually ask standard leetcode problems in this round. They will ask you more realistic problems to see how you approach them.</p><p>Even if very difficult problems are asked here, interviewers are more interested in knowing what approach you have taken to solve the problem than the final output alone.</p><h2 id="how-effective-are-these-interviews">How effective are these interviews?</h2><p>DSA interviews do a very fair estimation of your</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/04/How-effective-are-these-interviews.png" class="kg-image" alt="Why Do Companies Ask DSA Questions in Interviews?" loading="lazy" width="1920" height="1166" srcset="https://www.crio.do/blog/content/images/size/w600/2022/04/How-effective-are-these-interviews.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/04/How-effective-are-these-interviews.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/04/How-effective-are-these-interviews.png 1600w, https://www.crio.do/blog/content/images/2022/04/How-effective-are-these-interviews.png 1920w" sizes="(min-width: 720px) 720px"></figure><p>Debugging skills are particularly assessed during the personal interviews.</p><h2 id="in-reality%E2%80%A6">In Reality&#x2026;</h2><p>PSDS has turned into a filtering criterion that everyone prepares too much for. A lot of companies end up asking some of the most standard questions, and since these are standard, if you have prepared for the exact same question, you will be able to solve it.</p><p>The idea of assessing the candidate&apos;s cognitive, problem-solving and coding abilities gets lost in the process.</p><p>Practicing some important 400+ leetcode problems sometimes becomes sufficient to crack online screening rounds.</p><p>To overcome this, companies keep bumping up the difficulty level of the problems, so that they can differentiate between candidates who have prepared in advance by solving a large number of problems and the ones who have genuinely solved the problem then and there.</p><p>For this reason, the DSA interviews have become <strong>5 times more difficult</strong> than what is necessary for you to become a good software developer.</p><h2 id="how-much-dsa-do-you-really-need-to-study">How much DSA do you really need to study?</h2><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/04/How-much-DSA-do-you-really-need-to-study.png" class="kg-image" alt="Why Do Companies Ask DSA Questions in Interviews?" loading="lazy" width="1920" height="867" srcset="https://www.crio.do/blog/content/images/size/w600/2022/04/How-much-DSA-do-you-really-need-to-study.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/04/How-much-DSA-do-you-really-need-to-study.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/04/How-much-DSA-do-you-really-need-to-study.png 1600w, https://www.crio.do/blog/content/images/2022/04/How-much-DSA-do-you-really-need-to-study.png 1920w" sizes="(min-width: 720px) 720px"></figure><h2 id="conclusion">Conclusion</h2><p>Practice and expansion of your knowledge in DSA are going to be key to cracking interviews. </p><p>Ensure a good chunk of your time for this before you start applying for companies. </p><p>Here&apos;s a 3 stage DSA preparation plan to get you started.</p><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><p>All the best! And Good Luck!</p>]]></content:encoded></item><item><title><![CDATA[Why Do Companies Ask DSA Questions in Interviews?]]></title><description><![CDATA[Most of the interviews for technical roles in product-based companies are focused on measuring the Data Structures and Algorithms knowledge of the candidates. But, why such emphasis on this topic? Read on to know more...]]></description><link>https://www.crio.do/blog/why-learn-data-structures-and-algorithms/</link><guid isPermaLink="false">624fbda3c50e7c6cd272d46a</guid><category><![CDATA[Career Guidance]]></category><category><![CDATA[Data Structures and Algorithms]]></category><dc:creator><![CDATA[Abheetha Pradhan]]></dc:creator><pubDate>Tue, 23 Aug 2022 13:26:00 GMT</pubDate><media:content url="https://www.crio.do/blog/content/images/2022/04/Why-do-companies-ask-DSA-questions.png" medium="image"/><content:encoded><![CDATA[<figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/ZUBoG6j-Vco?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><h2 id="what-is-dsa">What is DSA?</h2><img src="https://www.crio.do/blog/content/images/2022/04/Why-do-companies-ask-DSA-questions.png" alt="Why Do Companies Ask DSA Questions in Interviews?"><p>DSA stands for Data Structures and Algorithms. It is also sometimes referred to as PSDS - Problem Solving Data Structures. DSA is applied in problem-solving and enables developers to learn to write efficient code. The quality of the code can be judged by how much memory and time it consumes. The lesser memory the code consumes and the faster it runs, the more efficient it is.</p><h2 id="why-is-dsa-important">Why is DSA important?</h2><p>A person equipped with strong DSA skills will have better and more efficient approaches to solving a problem than someone who is not aware of DSA concepts. </p><p>You might not apply DSA directly in your job, but DSA is the foundation of computer science. You will certainly be a better software engineer if you have mastered DSA. So it&apos;s advisable to slowly master it at the beginning of your IT career itself.</p><h2 id="how-do-companies-use-dsa">How do companies use DSA?</h2><p>Companies use DSA in mainly two ways - </p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/04/How-do-companies-use-DSA.png" class="kg-image" alt="Why Do Companies Ask DSA Questions in Interviews?" loading="lazy" width="1920" height="687" srcset="https://www.crio.do/blog/content/images/size/w600/2022/04/How-do-companies-use-DSA.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/04/How-do-companies-use-DSA.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/04/How-do-companies-use-DSA.png 1600w, https://www.crio.do/blog/content/images/2022/04/How-do-companies-use-DSA.png 1920w" sizes="(min-width: 720px) 720px"></figure><p>In both of these cases, you as a candidate are required to write code to solve a problem that uses DSA.</p><p>Websites like HackerRank, LeetCode, and CodeForces have large sets of problems ranging from easy, medium, and hard levels of difficulty. Anybody can sign up on these websites and solve problems by writing code in any of the major programming languages and hone their skills in PSDS. </p><p>A lot of companies also use these websites to set interview questions. These websites have powerful evaluation tools to check your program for different test cases and also to test your program for plagiarism.</p><h3 id="1-online-screening">1. Online Screening</h3><p>Companies use DSA to filter candidates. A company could have as many as 500 applicants and they might need to shortlist 20 candidates. DSA coding assessments serve as an objective way to filter the candidates.</p><p>By doing this,</p><ol><li>The company spends &lt; 1-2 hors setting problems on HackerRank and get automated leaderboard performance results back from Hackerrank.</li><li>Candidates don&#x2019;t spend more than 2 hours of their time going to the next stage of the interview.<br></li></ol><p>Without doing this,</p><ol><li>The company asks all the 500 applicants to build a project for 12 hours</li><li>The company has to build automatic assessments for this project which is 20+ hours of work for their engineers</li><li>Candidates who get rejected have wasted 12 hours of their precious time. <br></li></ol><p><strong>How are coding assessments fair?</strong></p><ol><li>The coding ability of the candidates is judged.</li><li>Depth of DSA knowledge is judged based on the difficulty level of the problems set.<br></li></ol><p>But there are some disadvantages to this method of filtering candidates</p><p><strong>1. Plagiarism</strong></p><p>Anybody can take up the online test unless strict measures of proctoring are implemented. </p><p><strong>2. Problem Difficulty</strong></p><p>The difficulty of the problems is progressively raised with a larger number of candidates. This is because companies don&#x2019;t want all candidates to have the same score; they need a stack rank.</p><p>Because of this, online coding assessments can become too hard, more than what is required for the job.</p><h3 id="2-personal-interviews">2. Personal interviews</h3><p>Apart from coding ability &amp; DSA knowledge, the personal interview rounds aim at assessing a few more skills of the candidate:</p><p><strong>Problem-solving ability</strong></p><p>They evaluate if you are able to ask the right questions, come up with multiple solutions, are able to cover all aspects of the problem, make the right trade-offs, etc.</p><p><strong>Debugging ability</strong></p><p>The interviewer will also assess you by checking if you are able to structurally debug the code when you face issues.</p><p>In other terms, during online assessments, companies usually look for the final output of the code you have written. Whereas during personal interviews, the interviewer is interested in understanding your approach to solving the problem.</p><p>Well-prepared interviewers don&#x2019;t usually ask standard leetcode problems in this round. They will ask you more realistic problems to see how you approach them.</p><p>Even if very difficult problems are asked here, interviewers are more interested in knowing what approach you have taken to solve the problem than the final output alone.</p><h2 id="how-effective-are-these-interviews">How effective are these interviews?</h2><p>DSA interviews do a very fair estimation of your</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/04/How-effective-are-these-interviews.png" class="kg-image" alt="Why Do Companies Ask DSA Questions in Interviews?" loading="lazy" width="1920" height="1166" srcset="https://www.crio.do/blog/content/images/size/w600/2022/04/How-effective-are-these-interviews.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/04/How-effective-are-these-interviews.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/04/How-effective-are-these-interviews.png 1600w, https://www.crio.do/blog/content/images/2022/04/How-effective-are-these-interviews.png 1920w" sizes="(min-width: 720px) 720px"></figure><p>Debugging skills are particularly assessed during the personal interviews.</p><h2 id="in-reality%E2%80%A6">In Reality&#x2026;</h2><p>PSDS has turned into a filtering criterion that everyone prepares too much for. A lot of companies end up asking some of the most standard questions, and since these are standard, if you have prepared for the exact same question, you will be able to solve it.</p><p>The idea of assessing the candidate&apos;s cognitive, problem-solving and coding abilities gets lost in the process.</p><p>Practicing some important 400+ leetcode problems sometimes becomes sufficient to crack online screening rounds.</p><p>To overcome this, companies keep bumping up the difficulty level of the problems, so that they can differentiate between candidates who have prepared in advance by solving a large number of problems and the ones who have genuinely solved the problem then and there.</p><p>For this reason, the DSA interviews have become <strong>5 times more difficult</strong> than what is necessary for you to become a good software developer.</p><h2 id="how-much-dsa-do-you-really-need-to-study">How much DSA do you really need to study?</h2><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/04/How-much-DSA-do-you-really-need-to-study.png" class="kg-image" alt="Why Do Companies Ask DSA Questions in Interviews?" loading="lazy" width="1920" height="867" srcset="https://www.crio.do/blog/content/images/size/w600/2022/04/How-much-DSA-do-you-really-need-to-study.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/04/How-much-DSA-do-you-really-need-to-study.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/04/How-much-DSA-do-you-really-need-to-study.png 1600w, https://www.crio.do/blog/content/images/2022/04/How-much-DSA-do-you-really-need-to-study.png 1920w" sizes="(min-width: 720px) 720px"></figure><h2 id="conclusion">Conclusion</h2><p>Practice and expansion of your knowledge in DSA are going to be key to cracking interviews. </p><p>Ensure a good chunk of your time for this before you start applying for companies. </p><p>Here&apos;s a 3 stage DSA preparation plan to get you started.</p><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><p>All the best! And Good Luck!</p>]]></content:encoded></item><item><title><![CDATA[Understanding Binary Search Algorithm]]></title><description><![CDATA[A classic example of Divide and Conquer for solving complex problems.]]></description><link>https://www.crio.do/blog/understanding-binary-search-algorithm-2/</link><guid isPermaLink="false">66c783bc134c11095afa9307</guid><category><![CDATA[Data Structures and Algorithms]]></category><dc:creator><![CDATA[Harshita Bansal]]></dc:creator><pubDate>Fri, 12 Aug 2022 08:17:58 GMT</pubDate><media:content url="https://www.crio.do/blog/content/images/2022/08/Understanding-Binary-Search-Algorithm.png" medium="image"/><content:encoded><![CDATA[<img src="https://www.crio.do/blog/content/images/2022/08/Understanding-Binary-Search-Algorithm.png" alt="Understanding Binary Search Algorithm"><p>What do Hitler, Napoleon, and Julius Caesar have in common? </p><p>They have all won major battles using the simple yet effective method of divide and conquer. </p><p>Divide and conquer has always been a fantastic approach for solving complex problems. This also stands true for data retrieval.<br><strong>Binary search</strong>, based on the principle of divide and conquer, is a widely used search algorithm. <br></p><figure class="kg-card kg-image-card"><img src="https://lh5.googleusercontent.com/k5t-qcxLv8ndlfF738Hv1ddtkPBuzfkdZl9Z6kHJr7XQmuHXYT2rqCnzd8i71Yuk4Fq25NB-UM7JiyDcxaEKDTh-yOfjx94Vh4D1DYC8nBPF0xVBcZd5RT4f96edCXhK4_xLC5Of" class="kg-image" alt="Understanding Binary Search Algorithm" loading="lazy"></figure><h2 id="try-it-yourself">Try it yourself</h2><p>Consider that you want to look for the word &#x2018;Search&#x2019; in the dictionary.</p><p>Intuitively, you would open the dictionary in the middle and see if the first letter of the page comes after or before the letter &#x2018;S&#x2019;. </p><p>Let&#x2019;s say that the letter you arrived at is &#x2018;N&#x2019;. Since &#x2018;S&#x2019; comes after &#x2018;N&#x2019; in the alphabet, you would then ignore the first half of the dictionary and divide the second half into two parts.</p><p>Now, say that you arrived at the letter &#x2018;T&#x2019;.</p><p>This process continues until you intuitively take to linear searching through pages of the letter &#x2018;S&#x2019; to find the word.</p><p>Now consider a much bigger dataset. Let us say you want to find your name in a register that contains the names of all people in the world. If you go linearly, this might take you hours or even days to find your name. However, the same can be accomplished by binary search in no more than 33 iterations. <br></p><h1 id="prerequisites-to-binary-search">Prerequisites to Binary Search</h1><p>Binary search has three simple prerequisites:</p><ol><li>Your dataset must be sorted</li><li>Your dataset must be sorted</li><li>Your dataset MUST be sorted</li></ol><p>Okay, now that you have a sorted dataset, let&#x2019;s begin searching!<br></p><figure class="kg-card kg-image-card kg-width-wide"><img src="https://lh4.googleusercontent.com/MJ65WEy1BlbdSOxoh0UF3iG5QYgHQj4X5mMJMPUIx1AjIOeA6Wow3L0Sx2fpTtBLDuht728YWNCcCXtmcGozxLy8PPkL3Jqz1Zn78q7iEz8wmmbNdLJO6SCE5AdWnuRz6QomdIUb" class="kg-image" alt="Understanding Binary Search Algorithm" loading="lazy"></figure><h1 id="what-is-binary-search">What is binary search?</h1><p>Binary search, also known as half-interval search, logarithmic search, or binary chop in computer science, is a search technique that locates a target value inside a sorted array. It does so by dividing the sorted array and focussing on only the &#x201C;relevant&#x201D; or &#x201C;valuable&#x201D; half and ignoring the rest.</p><h2 id="search-algorithm">Search Algorithm</h2><ol><li>The required element should be compared to the centre element.</li><li>We return the mid index if the required element is equal to the middle element.</li><li>Else If it is bigger than the mid element, it can only be found after the mid element in the right half subarray. As a result, we repeat the process for the right half.</li><li>Otherwise, repeat for the left half.</li></ol><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/08/Sequential-Search.gif" class="kg-image" alt="Understanding Binary Search Algorithm" loading="lazy" width="600" height="500"></figure><h1 id="try-it-yourself-1">Try it yourself</h1><p>Try implementing binary search in your preferred language using this algorithm. You may take help from the code snippets below. Feel free to reach out to us in the comments section if you find any bugs!</p><h2 id="code-c-recursive-implementation">Code: C (Recursive implementation)<br></h2><figure class="kg-card kg-image-card"><img src="https://lh5.googleusercontent.com/HGgMRPxkQUySPrcHrYyFR_aoewhXw2StjtGZnlQzzGpsePZbnryx2vrMwf97-Yun4LU32AXeBEdn85xr23jWzVZZy8CCac9dij97G21hZeTATndRUxdTyDWDdHBfM-olqK1YQKok" class="kg-image" alt="Understanding Binary Search Algorithm" loading="lazy"></figure><p>Output: Element is present at index 4</p><h2 id="code-c-iterative-implementation">Code: C++ (Iterative Implementation)<br></h2><figure class="kg-card kg-image-card"><img src="https://lh5.googleusercontent.com/QjIeMgBNbUdbsE2TirJZGXFmXD0wkC5g9aabmLGqWYUZpEGzAchakXVBFibRURGrxWg8v5YujwZccxferCqiRwpXR0CTQ-XuZcFwZ2UzcwwN9tER0TrxExdtSlYU4ZbIey4F45Ma" class="kg-image" alt="Understanding Binary Search Algorithm" loading="lazy"></figure><p>Output: Element is present at index 4</p><h2 id="code-python3-recursive-implementation">Code: Python3 (Recursive implementation)<br></h2><figure class="kg-card kg-image-card"><img src="https://lh3.googleusercontent.com/bQj_4BBCOgAEgFgpiU2KgKKr3JtwoU-EQQ0v6u0VMd26sTzXoEY4fEaqHycmbUW2iQhPj1_RnqJ53e7QIzf1Y6H7C2z1m_DGdLJ-h99p3MljsJKrOR0jPOFVs0CoF0-7lUDx2Ja5" class="kg-image" alt="Understanding Binary Search Algorithm" loading="lazy"></figure><p>Output: Element is present at index 4</p><h2 id="code-java-iterative-implementation">Code: Java (Iterative implementation)<br></h2><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/Agbkj8zTl-DfEVHPO9vTnjvxChxVOBrln6GV_7bgMfMUusMeKHD29QKoppo6gq2MHPjF9bKEo4qHEjL5Wj0T5XAycY5MQvREIpcp9FGuAligiUuJ3nprVppGwfzb3VEF7OVhEio2" class="kg-image" alt="Understanding Binary Search Algorithm" loading="lazy"></figure><p>Output: Element found at index 4</p><h2 id="time-complexity-analysis">Time complexity analysis</h2><p>While implementing binary search, the target element may be at three kinds of positions:</p><ol><li>Middle of the array (Best case)</li><li>First or last element of the array (Worst case)</li><li>Anywhere except the cases above (Average case)</li></ol><p>The Best case time complexity of the binary search algorithm is O(1).</p><p>The Average and Worst case time complexity is O(log2n).</p><p>This time complexity is significantly better than the linear search algorithm, whose average and worst-case time complexity is O(n).</p><h1 id="add-finishing-touches-to-your-knowledge">Add finishing touches to your knowledge!</h1><p>Since Binary search is a quick way for searching through sorted databases, it is often used in debugging. Suppose you have 100 versions of a code, each of which is different from the other. The 1st version displays the correct output, but the 100th version doesn&#x2019;t. </p><p>An efficient way to find the broken version would be to run a binary search through all the versions. The versions are logged in a Version Control System in sorted order, so don&#x2019;t worry about that. Check out the code in the 50th release, build it, and see if the bug is still there. </p><p>Continue dividing until you discover when the bug was introduced. This approach comes in quite handy especially if you make small commits.</p><h2 id="test-your-understanding">Test your understanding</h2><p><strong>Q1.</strong> Given an input array = {5,9,11,15,21} and target element = 21. How many iterations are done until the element is found?</p><ol><li>5</li><li>2</li><li>3</li><li>4</li></ol><p><strong>Q2.</strong> Given an array = {23, 41, 52, 68, 84, 91,102} and target element = 102. What are the mid values (corresponding array elements) generated in the first and second iterations?</p><ol><li>68 and 91</li><li>68 and 102</li><li>52 and 84</li><li>52 and 91</li></ol><h1 id="improvements-on-binary-search-algorithm">Improvements on Binary Search algorithm:</h1><p>Congrats! You have learned how to implement the binary search algorithm. But there is always room for improvement, right?</p><p>One possible way is to reduce the worst-case time complexity to O(1); you may check if the target element is equal to the first or last element of the array right in the beginning. </p><p>You discovered the wonders of Divide and Conquer and explored binary search in detail! So, the next time you are faced with looking through a large dataset, like a dictionary or your closet, look through its sections instead :)<br></p><hr><h2 id="before-you-leave">Before you leave...</h2><p>Binary search forms the basis of a Binary Search Tree.</p><p>If you want to learn about it in a similar article, drop a comment below and let us know your interest. </p><p>And if you enjoyed learning the fundamentals of binary search through this article, share the knowledge with your fellow programmers and your social circle. Maybe someone out there really needs this resource, and you might be helping them out by sharing it.</p><p>Happy Coding!</p>]]></content:encoded></item><item><title><![CDATA[Understanding Binary Search Algorithm]]></title><description><![CDATA[A classic example of Divide and Conquer for solving complex problems.]]></description><link>https://www.crio.do/blog/understanding-binary-search-algorithm/</link><guid isPermaLink="false">60e5a8123c06050ca1329879</guid><category><![CDATA[Data Structures and Algorithms]]></category><dc:creator><![CDATA[Harshita Bansal]]></dc:creator><pubDate>Fri, 12 Aug 2022 08:17:58 GMT</pubDate><media:content url="https://www.crio.do/blog/content/images/2022/08/Understanding-Binary-Search-Algorithm.png" medium="image"/><content:encoded><![CDATA[<img src="https://www.crio.do/blog/content/images/2022/08/Understanding-Binary-Search-Algorithm.png" alt="Understanding Binary Search Algorithm"><p>What do Hitler, Napoleon, and Julius Caesar have in common? </p><p>They have all won major battles using the simple yet effective method of divide and conquer. </p><p>Divide and conquer has always been a fantastic approach for solving complex problems. This also stands true for data retrieval.<br><strong>Binary search</strong>, based on the principle of divide and conquer, is a widely used search algorithm. <br></p><figure class="kg-card kg-image-card"><img src="https://lh5.googleusercontent.com/k5t-qcxLv8ndlfF738Hv1ddtkPBuzfkdZl9Z6kHJr7XQmuHXYT2rqCnzd8i71Yuk4Fq25NB-UM7JiyDcxaEKDTh-yOfjx94Vh4D1DYC8nBPF0xVBcZd5RT4f96edCXhK4_xLC5Of" class="kg-image" alt="Understanding Binary Search Algorithm" loading="lazy"></figure><h2 id="try-it-yourself">Try it yourself</h2><p>Consider that you want to look for the word &#x2018;Search&#x2019; in the dictionary.</p><p>Intuitively, you would open the dictionary in the middle and see if the first letter of the page comes after or before the letter &#x2018;S&#x2019;. </p><p>Let&#x2019;s say that the letter you arrived at is &#x2018;N&#x2019;. Since &#x2018;S&#x2019; comes after &#x2018;N&#x2019; in the alphabet, you would then ignore the first half of the dictionary and divide the second half into two parts.</p><p>Now, say that you arrived at the letter &#x2018;T&#x2019;.</p><p>This process continues until you intuitively take to linear searching through pages of the letter &#x2018;S&#x2019; to find the word.</p><p>Now consider a much bigger dataset. Let us say you want to find your name in a register that contains the names of all people in the world. If you go linearly, this might take you hours or even days to find your name. However, the same can be accomplished by binary search in no more than 33 iterations. <br></p><h1 id="prerequisites-to-binary-search">Prerequisites to Binary Search</h1><p>Binary search has three simple prerequisites:</p><ol><li>Your dataset must be sorted</li><li>Your dataset must be sorted</li><li>Your dataset MUST be sorted</li></ol><p>Okay, now that you have a sorted dataset, let&#x2019;s begin searching!<br></p><figure class="kg-card kg-image-card kg-width-wide"><img src="https://lh4.googleusercontent.com/MJ65WEy1BlbdSOxoh0UF3iG5QYgHQj4X5mMJMPUIx1AjIOeA6Wow3L0Sx2fpTtBLDuht728YWNCcCXtmcGozxLy8PPkL3Jqz1Zn78q7iEz8wmmbNdLJO6SCE5AdWnuRz6QomdIUb" class="kg-image" alt="Understanding Binary Search Algorithm" loading="lazy"></figure><h1 id="what-is-binary-search">What is binary search?</h1><p>Binary search, also known as half-interval search, logarithmic search, or binary chop in computer science, is a search technique that locates a target value inside a sorted array. It does so by dividing the sorted array and focussing on only the &#x201C;relevant&#x201D; or &#x201C;valuable&#x201D; half and ignoring the rest.</p><h2 id="search-algorithm">Search Algorithm</h2><ol><li>The required element should be compared to the centre element.</li><li>We return the mid index if the required element is equal to the middle element.</li><li>Else If it is bigger than the mid element, it can only be found after the mid element in the right half subarray. As a result, we repeat the process for the right half.</li><li>Otherwise, repeat for the left half.</li></ol><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/08/Sequential-Search.gif" class="kg-image" alt="Understanding Binary Search Algorithm" loading="lazy" width="600" height="500"></figure><h1 id="try-it-yourself-1">Try it yourself</h1><p>Try implementing binary search in your preferred language using this algorithm. You may take help from the code snippets below. Feel free to reach out to us in the comments section if you find any bugs!</p><h2 id="code-c-recursive-implementation">Code: C (Recursive implementation)<br></h2><figure class="kg-card kg-image-card"><img src="https://lh5.googleusercontent.com/HGgMRPxkQUySPrcHrYyFR_aoewhXw2StjtGZnlQzzGpsePZbnryx2vrMwf97-Yun4LU32AXeBEdn85xr23jWzVZZy8CCac9dij97G21hZeTATndRUxdTyDWDdHBfM-olqK1YQKok" class="kg-image" alt="Understanding Binary Search Algorithm" loading="lazy"></figure><p>Output: Element is present at index 4</p><h2 id="code-c-iterative-implementation">Code: C++ (Iterative Implementation)<br></h2><figure class="kg-card kg-image-card"><img src="https://lh5.googleusercontent.com/QjIeMgBNbUdbsE2TirJZGXFmXD0wkC5g9aabmLGqWYUZpEGzAchakXVBFibRURGrxWg8v5YujwZccxferCqiRwpXR0CTQ-XuZcFwZ2UzcwwN9tER0TrxExdtSlYU4ZbIey4F45Ma" class="kg-image" alt="Understanding Binary Search Algorithm" loading="lazy"></figure><p>Output: Element is present at index 4</p><h2 id="code-python3-recursive-implementation">Code: Python3 (Recursive implementation)<br></h2><figure class="kg-card kg-image-card"><img src="https://lh3.googleusercontent.com/bQj_4BBCOgAEgFgpiU2KgKKr3JtwoU-EQQ0v6u0VMd26sTzXoEY4fEaqHycmbUW2iQhPj1_RnqJ53e7QIzf1Y6H7C2z1m_DGdLJ-h99p3MljsJKrOR0jPOFVs0CoF0-7lUDx2Ja5" class="kg-image" alt="Understanding Binary Search Algorithm" loading="lazy"></figure><p>Output: Element is present at index 4</p><h2 id="code-java-iterative-implementation">Code: Java (Iterative implementation)<br></h2><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/Agbkj8zTl-DfEVHPO9vTnjvxChxVOBrln6GV_7bgMfMUusMeKHD29QKoppo6gq2MHPjF9bKEo4qHEjL5Wj0T5XAycY5MQvREIpcp9FGuAligiUuJ3nprVppGwfzb3VEF7OVhEio2" class="kg-image" alt="Understanding Binary Search Algorithm" loading="lazy"></figure><p>Output: Element found at index 4</p><h2 id="time-complexity-analysis">Time complexity analysis</h2><p>While implementing binary search, the target element may be at three kinds of positions:</p><ol><li>Middle of the array (Best case)</li><li>First or last element of the array (Worst case)</li><li>Anywhere except the cases above (Average case)</li></ol><p>The Best case time complexity of the binary search algorithm is O(1).</p><p>The Average and Worst case time complexity is O(log2n).</p><p>This time complexity is significantly better than the linear search algorithm, whose average and worst-case time complexity is O(n).</p><h1 id="add-finishing-touches-to-your-knowledge">Add finishing touches to your knowledge!</h1><p>Since Binary search is a quick way for searching through sorted databases, it is often used in debugging. Suppose you have 100 versions of a code, each of which is different from the other. The 1st version displays the correct output, but the 100th version doesn&#x2019;t. </p><p>An efficient way to find the broken version would be to run a binary search through all the versions. The versions are logged in a Version Control System in sorted order, so don&#x2019;t worry about that. Check out the code in the 50th release, build it, and see if the bug is still there. </p><p>Continue dividing until you discover when the bug was introduced. This approach comes in quite handy especially if you make small commits.</p><h2 id="test-your-understanding">Test your understanding</h2><p><strong>Q1.</strong> Given an input array = {5,9,11,15,21} and target element = 21. How many iterations are done until the element is found?</p><ol><li>5</li><li>2</li><li>3</li><li>4</li></ol><p><strong>Q2.</strong> Given an array = {23, 41, 52, 68, 84, 91,102} and target element = 102. What are the mid values (corresponding array elements) generated in the first and second iterations?</p><ol><li>68 and 91</li><li>68 and 102</li><li>52 and 84</li><li>52 and 91</li></ol><h1 id="improvements-on-binary-search-algorithm">Improvements on Binary Search algorithm:</h1><p>Congrats! You have learned how to implement the binary search algorithm. But there is always room for improvement, right?</p><p>One possible way is to reduce the worst-case time complexity to O(1); you may check if the target element is equal to the first or last element of the array right in the beginning. </p><p>You discovered the wonders of Divide and Conquer and explored binary search in detail! So, the next time you are faced with looking through a large dataset, like a dictionary or your closet, look through its sections instead :)<br></p><hr><h2 id="before-you-leave">Before you leave...</h2><p>Binary search forms the basis of a Binary Search Tree.</p><p>If you want to learn about it in a similar article, drop a comment below and let us know your interest. </p><p>And if you enjoyed learning the fundamentals of binary search through this article, share the knowledge with your fellow programmers and your social circle. Maybe someone out there really needs this resource, and you might be helping them out by sharing it.</p><p>Happy Coding!</p>]]></content:encoded></item><item><title><![CDATA[Types of Binary Tree Data Structures - How to Use - Explained With Examples and Activities]]></title><description><![CDATA[A binary tree is made up of nodes that can have two children. In a binary tree, any node can have a maximum of 0, 1, or 2 nodes. ]]></description><link>https://www.crio.do/blog/binary-tree-data-structures-2/</link><guid isPermaLink="false">66c783bc134c11095afa931d</guid><category><![CDATA[Data Structures and Algorithms]]></category><dc:creator><![CDATA[Sandipan Das]]></dc:creator><pubDate>Fri, 17 Jun 2022 10:01:00 GMT</pubDate><media:content url="https://www.crio.do/blog/content/images/2022/02/Types-of-Binary-Trees.png" medium="image"/><content:encoded><![CDATA[<img src="https://www.crio.do/blog/content/images/2022/02/Types-of-Binary-Trees.png" alt="Types of Binary Tree Data Structures - How to Use - Explained With Examples and Activities"><p>A binary tree is defined as a <a href="https://www.crio.do/blog/tag/data-structures-and-algorithms/?utm_source=blog-int">data structure</a> that is non-linear in nature and follows a hierarchical structure. Also, it has a maximum of two children nodes for each of its parent nodes. The word binary is self-explanatory since it is associated with the number two. </p><p>Every node in a binary tree is associated with three distinct fields, namely:</p><ul><li>Data element</li><li>Reference to the left child node</li><li>Reference to the right child node</li></ul><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Diagram-of-Binary-Tree.png" class="kg-image" alt="Types of Binary Tree Data Structures - How to Use - Explained With Examples and Activities" loading="lazy" width="2000" height="1245" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Diagram-of-Binary-Tree.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Diagram-of-Binary-Tree.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/Diagram-of-Binary-Tree.png 1600w, https://www.crio.do/blog/content/images/2022/02/Diagram-of-Binary-Tree.png 2334w" sizes="(min-width: 720px) 720px"></figure><p>Given above is a simple diagram of a binary tree data structure. As you can see, the tree has a hierarchical structure and descends from a root node (with value 1). You may have also noticed that each of the nodes has at most 2 children nodes except for the leaf nodes. This is what categorizes this tree as a binary tree.</p><h1 id="basic-tree-terminology">Basic Tree Terminology</h1><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Basic-Tree-Terminology.png" class="kg-image" alt="Types of Binary Tree Data Structures - How to Use - Explained With Examples and Activities" loading="lazy" width="1801" height="2437" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Basic-Tree-Terminology.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Basic-Tree-Terminology.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/Basic-Tree-Terminology.png 1600w, https://www.crio.do/blog/content/images/2022/02/Basic-Tree-Terminology.png 1801w" sizes="(min-width: 720px) 720px"></figure><h2 id="root-node">Root Node</h2><p>The initial node in a tree data structure is known as the Root Node. A root node is required for every tree. The root node is the starting point for the tree data structure. There can only be one root node in any tree. A tree can never have more than one root node.</p><h2 id="edge">Edge</h2><p>The EDGE is the connecting line between any two nodes in a tree data structure. There will be a maximum limit of &apos;N-1&apos; number of edges in a tree with &apos;N&apos; nodes.</p><h2 id="parent-node">Parent Node</h2><p>In a tree data structure, the predecessor node of any given node is called a parent node. In simpler terms, any node which has one or more children nodes associated with it is termed a parent node.</p><h2 id="child-node">Child Node</h2><p>In a tree data structure, the successor node of any given node is called a child node. In simpler terms, the descendant node of a given parent node is termed a child node.</p><h2 id="leaf-node">Leaf Node</h2><p>In a tree data structure, a terminating node without any subsequent children nodes is called a leaf node.</p><h2 id="internal-node">Internal Node</h2><p>In a tree data structure, any node with one or more children nodes associated with it is called an internal node.</p><h2 id="degree">Degree</h2><p>The total number of children nodes associated with a given node in a tree is called a degree.</p><h2 id="level">Level</h2><p>In a tree data structure, each step from the top to the bottom constitutes a level. For example, the root node is at level 0, the children of the root node are at level 1, and so on.</p><h2 id="height">Height</h2><p>The total number of edges in the longest path from a leaf node to any given node in a tree data structure is defined as the height of the given node.</p><p>The height associated with the root node is also the height of the tree data structure.</p><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure><h2 id="properties-of-binary-tree-data-structure"><br>Properties of Binary Tree Data Structure</h2><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Properties-of-Binary-Tree-Data-Structure.png" class="kg-image" alt="Types of Binary Tree Data Structures - How to Use - Explained With Examples and Activities" loading="lazy" width="1801" height="1601" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Properties-of-Binary-Tree-Data-Structure.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Properties-of-Binary-Tree-Data-Structure.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/Properties-of-Binary-Tree-Data-Structure.png 1600w, https://www.crio.do/blog/content/images/2022/02/Properties-of-Binary-Tree-Data-Structure.png 1801w" sizes="(min-width: 720px) 720px"></figure><ul><li>The maximum number of nodes at each level &#x2018;i&#x2019; of a binary tree is given by 2^i</li><li>The minimum number of nodes at height &#x2018;h&#x2019; of a binary tree is given by (h+1)</li><li>The maximum number of nodes at height &#x2018;h&#x2019; of a binary tree is given by (2^(h+1))-1</li></ul><h2 id="various-types-of-binary-tree-data-structure">Various Types of Binary Tree Data Structure</h2><h3 id="proper-binary-tree">Proper Binary Tree</h3><p>It is a type of binary tree that has either two children or zero children for each node. It is also called a <strong>strict binary tree</strong>. Given below is a simple diagram to illustrate a proper binary tree.</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Proper-Binary-Tree.png" class="kg-image" alt="Types of Binary Tree Data Structures - How to Use - Explained With Examples and Activities" loading="lazy" width="2000" height="1383" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Proper-Binary-Tree.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Proper-Binary-Tree.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/Proper-Binary-Tree.png 1600w, https://www.crio.do/blog/content/images/2022/02/Proper-Binary-Tree.png 2050w" sizes="(min-width: 720px) 720px"></figure><p>It&apos;s clearly observable that every node (except the leaf nodes) has strictly 2 children. That is why it is also known as a strict binary tree.</p><h3 id="complete-binary-tree">Complete Binary Tree</h3><p>It is a type of binary tree data structure in which all internal nodes are completely filled except for the nodes at the last level. In the last level, the nodes must be filled from as left as possible. Given below is an example of a complete binary tree.</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Complete-Binary-Tree.png" class="kg-image" alt="Types of Binary Tree Data Structures - How to Use - Explained With Examples and Activities" loading="lazy" width="2000" height="1383" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Complete-Binary-Tree.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Complete-Binary-Tree.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/Complete-Binary-Tree.png 1600w, https://www.crio.do/blog/content/images/2022/02/Complete-Binary-Tree.png 2050w" sizes="(min-width: 720px) 720px"></figure><p><br>You can clearly observe that the nodes at the last level (marked 2 and 3) are filled from the left and are not necessarily filled.</p><h3 id="properties">Properties</h3><ul><li>Maximum number of nodes present in a complete binary tree of height h: <strong>2^(h+1)-1</strong>.</li><li>Minimum number of nodes present in a complete binary tree of height h: <strong>2^h</strong>.</li><li>Minimum height of a complete binary tree: <strong>log2(n+1) - 1.</strong></li></ul><h3 id="perfect-binary-tree">Perfect Binary Tree</h3><p>A tree is said to be a perfect binary tree if each of its nodes has strictly 2 children and all its leaf nodes are at the same level. Given below is a simple illustration of a perfect binary tree.</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Perfect-Binary-Tree.png" class="kg-image" alt="Types of Binary Tree Data Structures - How to Use - Explained With Examples and Activities" loading="lazy" width="2000" height="1383" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Perfect-Binary-Tree.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Perfect-Binary-Tree.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/Perfect-Binary-Tree.png 1600w, https://www.crio.do/blog/content/images/2022/02/Perfect-Binary-Tree.png 2050w" sizes="(min-width: 720px) 720px"></figure><p>As you see, the leaf nodes are all at the same level and all the internal nodes have exactly 2 children each. This is what categorizes it as a perfect binary tree.</p><h3 id="test-your-understanding">Test your understanding</h3><p>Given below is another example of a binary tree. Can you guess whether it is a perfect binary tree or not?</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Test-1.png" class="kg-image" alt="Types of Binary Tree Data Structures - How to Use - Explained With Examples and Activities" loading="lazy" width="2000" height="1489" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Test-1.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Test-1.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/Test-1.png 1600w, https://www.crio.do/blog/content/images/2022/02/Test-1.png 2050w" sizes="(min-width: 720px) 720px"></figure><p>Guess the answer??</p><p>.</p><p>.</p><p>Okay, the answer is a no. It&apos;s not a perfect binary tree for the simple reason that although the internal nodes have strictly 2 children each, the leaf nodes are not at the same level. This is an example of a proper binary tree instead.</p><h3 id="degenerate-binary-tree">Degenerate Binary Tree</h3><p>A binary tree is categorized as a degenerate binary tree if all its internal nodes have strictly one child node each except for the leaf node. Here&apos;s a diagram to illustrate this:</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Degenerate-Binary-Tree.png" class="kg-image" alt="Types of Binary Tree Data Structures - How to Use - Explained With Examples and Activities" loading="lazy" width="1429" height="1559" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Degenerate-Binary-Tree.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Degenerate-Binary-Tree.png 1000w, https://www.crio.do/blog/content/images/2022/02/Degenerate-Binary-Tree.png 1429w" sizes="(min-width: 720px) 720px"></figure><p>Here&apos;s another example to elucidate this concept:</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Degenerate-Binary-Tree-2.png" class="kg-image" alt="Types of Binary Tree Data Structures - How to Use - Explained With Examples and Activities" loading="lazy" width="1429" height="1559" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Degenerate-Binary-Tree-2.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Degenerate-Binary-Tree-2.png 1000w, https://www.crio.do/blog/content/images/2022/02/Degenerate-Binary-Tree-2.png 1429w" sizes="(min-width: 720px) 720px"></figure><p>In both the diagrams given above, each of the nodes in the tree has strictly one child node except for the terminating leaf node.</p><p>If all the nodes of a degenerate binary tree have a left child node only, it forms a left-skewed binary tree. </p><p>Similarly, if all nodes of the tree have a right child node only, it forms a right-skewed binary tree.</p><h2 id="balanced-binary-tree">Balanced Binary Tree</h2><p>In a balanced binary tree data structure, the height of the left and right subtrees for each node differ by at most 1. Some common examples of balanced binary trees are AVL trees and Red-Black trees. </p><p>Still unclear? Here&apos;s an example to understand balanced binary trees better.</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Balanced-Binary-Tree.png" class="kg-image" alt="Types of Binary Tree Data Structures - How to Use - Explained With Examples and Activities" loading="lazy" width="2000" height="1248" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Balanced-Binary-Tree.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Balanced-Binary-Tree.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/Balanced-Binary-Tree.png 1600w, https://www.crio.do/blog/content/images/2022/02/Balanced-Binary-Tree.png 2334w" sizes="(min-width: 720px) 720px"></figure><p>Node 1</p><ul><li>Height of the left subtree for given node = 2</li><li>Height of the right subtree for given node = 2</li><li>Difference = 0</li></ul><p>Node 2</p><ul><li>Height of the left subtree for given node = 1</li><li>Height of the right subtree for given node = 1</li><li>Difference = 0</li></ul><p>Node 3</p><ul><li>Height of the left subtree for given node = 1</li><li>Height of the right subtree for given node = 1</li><li>Difference = 0</li></ul><h3 id="test-your-understanding-1">Test your understanding</h3><p>Given below is another diagram of a binary tree. Can you guess whether it is a balanced binary tree or not?</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Test-2.png" class="kg-image" alt="Types of Binary Tree Data Structures - How to Use - Explained With Examples and Activities" loading="lazy" width="1814" height="1559" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Test-2.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Test-2.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2022/02/Test-2.png 1600w, https://www.crio.do/blog/content/images/2022/02/Test-2.png 1814w" sizes="(min-width: 720px) 720px"></figure><p>Struggling with the answer?</p><p>.</p><p>.</p><p>The correct answer is yes, it is a balanced binary tree, for the simple reason that the difference of at most 1 still holds for every internal node.</p><h2 id="binary-tree-implementation-in-c">Binary Tree Implementation in C++</h2><figure class="kg-card kg-image-card"><img src="https://lh6.googleusercontent.com/czmnAqHl-xPN_b_gH0Z21xcw_4_fEc3UJpcqQmepq2IYchdyrKaf2xaEAiRiXc0f9J3DCQmiopEyd1Eiw0ZLFZCefkbL3xjuU7AshvISPYssBSiwrAl6OAQCne4VtCsvBusU2Ug" class="kg-image" alt="Types of Binary Tree Data Structures - How to Use - Explained With Examples and Activities" loading="lazy"></figure><p>Given above is a simple C++ implementation of a binary tree data structure. Once executed, the following tree structure gets stored in memory:</p><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2022/02/Tree-Structure.png" class="kg-image" alt="Types of Binary Tree Data Structures - How to Use - Explained With Examples and Activities" loading="lazy" width="1443" height="928" srcset="https://www.crio.do/blog/content/images/size/w600/2022/02/Tree-Structure.png 600w, https://www.crio.do/blog/content/images/size/w1000/2022/02/Tree-Structure.png 1000w, https://www.crio.do/blog/content/images/2022/02/Tree-Structure.png 1443w" sizes="(min-width: 720px) 720px"></figure><p>1. First define a <strong>struct </strong>for the basic outline of your binary tree. Inside the main() function, you can observe that the <strong>root node</strong> is defined first which is assigned a value of <strong>10</strong>.</p><p>2. Next, define the <strong>left and right children nodes</strong> of the root node and assign values of <strong>20 </strong>and <strong>30 </strong>respectively.</p><p>3. This is the basic structure of a binary tree in C++.</p><p>4. Of course, you can expand on it to form more complex tree structures but this should be a good foundation to start with.</p><h2 id="real-life-implementation-of-tree-data-structure">Real-Life Implementation of Tree Data Structure<br></h2><ul><li>Machine learning employs decision-based <a href="https://www.crio.do/blog/top-10-sorting-algorithms/?utm_source=blog-int">algorithms</a> which are heavily reliant on the tree data structure.</li><li>SQL databases use B-Tree for indexing.</li><li>The file directory structure of our laptops or computers resembles a hierarchical tree structure.</li></ul><figure class="kg-card kg-image-card"><img src="https://www.crio.do/blog/content/images/2021/12/B-tree.png" class="kg-image" alt="Types of Binary Tree Data Structures - How to Use - Explained With Examples and Activities" loading="lazy" width="1991" height="447" srcset="https://www.crio.do/blog/content/images/size/w600/2021/12/B-tree.png 600w, https://www.crio.do/blog/content/images/size/w1000/2021/12/B-tree.png 1000w, https://www.crio.do/blog/content/images/size/w1600/2021/12/B-tree.png 1600w, https://www.crio.do/blog/content/images/2021/12/B-tree.png 1991w" sizes="(min-width: 720px) 720px"></figure><h2 id="conclusion">Conclusion</h2><p>Binary trees have a lot of applications in different fields including <a href="crio.do/blog/5-interesting-machine-learning-projects/?utm_source=blog-int">machine learning</a>, computing systems, <a href="https://www.crio.do/blog/tag/databases/?utm_source=blog-int">databases</a>, computer networking among many others. In other words, its applications are limitless.</p><p>Of course, we&apos;ve barely touched the surface when it comes to the conceptual aspects of binary trees. You can branch out from this article and explore the transversal <a href="https://www.crio.do/blog/top-10-sorting-algorithms/?utm_source=blog-int">algorithms</a> associated with trees, how it relates to other <a href="https://www.crio.do/blog/tag/data-structures-and-algorithms/?utm_source=blog-int">data structures</a> in existence, or you may as well crunch out some problems related to them.</p><p>Before you go, could you please share this article with your friends or on your social media handles? Also if you enjoyed reading this article, please don&apos;t forget to give a thumbs up.</p><p>Happy coding!!!</p><figure class="kg-card kg-embed-card"><iframe width="200" height="113" src="https://www.youtube.com/embed/8hzTSXS9G3k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></figure>]]></content:encoded></item></channel></rss>