Quick Sort Using Recursion (Theory + Complexity + Code)
In this video, we cover the quick sort algorithm. Including the theory, code implementation using recursion, space and time complexity analysis, along with comparison with merge sort. We also see how in-built sorting algorithms work.
Take part in the learning in public initiative! Share your learnings on LinkedIn and Twitter with #DSAwithKunal & don't forget to tag us!
👉 Resources
- Join Replit: join.replit.com/kunal-kushwaha
- Complete Java DSA playlist: • Java + DSA + Interview...
- Code, Assignments, & Notes: github.com/kunal-kushwaha/DSA...
➡️ Connect with me: kunalkushwaha.com
=========================================
Timestamps:
00:00 Introduction
03:01 What is Pivot?
04:43 Recursive Quick Sort
09:58 How to put pivot at correct position?
17:55 How to pick the pivot?
20:15 Complexity comparison of pivot positions
27:45 Important Notes
29:32 Hybrid Sorting Algorithms
31:49 Code for Quick Sort
39:12 Internal Sorting Algorithm
41:20 Outro
#sorting #placement #dsa #interviews
Пікірлер: 189
Kunal Kushwaha : "Your start is low , Your End is going to be high" :)
One of the best explanations I've seen for Quick Sort. The way he broke the concept down to its nuts and bolts is really amazing.
There's this merge sort and quick sort, people say its hard to understand this and so I left them and proceeded further in my DS journey. But I was damn sure you will make it easy and so listened to you and Now I know this . Thankyou KK Bhaiya 🤩
The confidence you have in your work, is empowering!! Keep that going
I have tried to understand merge sort and quick sort literally a thousand times. In college, classes, some time by me. I was not able to visualize how it is actually working with recursion, although I knew the code. But the way, you are simplifying the things and the way you have had the first recursion video done is just awesome. That first recursion video is quite important and on top of this you explained this sorting so well, kudos man!
Such a blessing to learn DSA with your videos.😇 Please complete the series.🙂
Before watching this vid, i was on gfg and javapoint understanding what quick sort was and my god, kunal has explined it so well and he hasnt copied what they did and I was blown by how easy he has made this!! Kudos bro,
I can't even express how much value it is providing us...hats off kunal bhai!
I remember plucking out my hair on recursion and sorting algos before stumbling on your videos. You explain it very well and its very intellectually satisfying to watch your videos as well.
I feel very confident whenever I learn from you, Thank You for existing, God bless you!!!
best lecture on yt for quick sort because it is the most efficient i have seen, but first watch the quick sort algorithm by striver, he will clear all the doubts if you have got any by watching this lecture , since i had lot of doubts . Once you understand the algorithm u can follow the code here . The concept will be crystal clear then .
Thanks for teaching us like no one did till now!! One small request, please make lectures on dynamic programming as well!!
Thank you Kunal Sir. You are always the best teacher. I never learned this sort by fearing the complexity. But now you made it a cakewalk. Always grateful.
this is good...i mean its good that you didnt advertise your videos in a humble way , because people wont know how good your videos are. PS i didnt realise how fast time went , the way you taught was very smooth and seemed like a story to me.
Hey Kunal, your lectures are valuably explained, and covers everything one should know sooner or later. For example after watching this QuickSort lecture, all I've to do is practice some question, I don't need to watch any more concept of this anywhere, and this is amazing. You and your video lectures are underrated, if this quality of lectures are provided by any EdTech they would have charged that course extravagant. Hope I'll be able to get ₹7Lakh/month 😂(Joking).
@KunalKushwaha
Жыл бұрын
you wont get 7 lakhs per month with dsa, it happens with dev
Kunal is very quick now 🔥 Thanks for the course ❣️
The way you have explained is great Kunal!
@KunalKushwaha
2 жыл бұрын
Thank You!
thank you I actually like this implementation better than other ones I have seen. this will stick with me, no doubt
Please Use Black Background for writing on the screen It doesn't affect eyes much 😊😊 Consider this Man
Thank you kunal finally understood the concept deeply.
U knw bro..i think u r inborn Guru not a professional teacher.may god bless u with all Happiness of this universe.🙏
thanks for uploading at this frequency. Hope that you will cover dp really soon. 👏🙌
As always brilliant explanation. I used to be scared of quick sort in my college days, but this video makes it seem really easy. Moreover, I was able to relate Step: placing pivot at the correct index with Binary Search step. In binary search, we search for a target element, assuming the array is sorted, and use the start and end indexes as pointers to the virtual array. Here we have to just place the pivot at the correct index, so instead of searching the target, we already have the target(i.e. pivot), we have to put at correct index and in this process we are ensuring elements less than pivot are on LHS, and elements greater than pivot are RHS.
Bhaiya ,aap sachii mein bohot achaa padhatee hoo. Thanks bhaiya for such a course
Wow, you are so good. Wish you to solve complex algorithms down the lane
Kunal, your tutorials are gems. I can pay for such quality content. But you choose not to. Love and Regards. Tweeting for better reach.
Best DSA COURSE on EARTH 🔥🔥 THANKU @kunal kushwaha
You are boosting my confidence day by day..🎉😊
Hey kunal, Thanks for this course.
Hey Kunal , why pivot element not place correct index after one recursion call ? Although the array is sorted in the end .
Very good explanation just loved it
Ohh damn, This was so well explained 45 minutes is totally worthy
@KunalKushwaha
2 жыл бұрын
Thank You!
@twi4458
2 жыл бұрын
Can anyone help me in understanding 24:50, How we got O(N^2). It is Linear Recurrence Relation, Right?
@ritviksaran6199
2 жыл бұрын
after each pass how does it ensure that pivot will end up in the correct position ?
If I use any other element as pivot instead of middle element, it gives stack overflow error. Can someone help me through this issue?(same algorithm)
Hey Kunal, what is the possibile time you take to complete dsa and start with Opps??
At 23:07 i dont get why we put pivot at middle while showing t(n) calculation ,at t=0 the left will be empty but right will be n-1 element does it mean we picked first element as pivot ?if not why we showing pivot in t(n) calculation why not just t k +t n-k + alfa n supposedly pivot is at the end of the array for better presentation pls enlighten me on this..
good job kunal and never gave up bro keep it up
In the merge sort video , I was little confused in the concepts of sorting algorithm through recursion but by this video , the previous confusion also got cleared . Thank you so much 😍😍😍
@KunalKushwaha
2 жыл бұрын
You're very welcome!
@vikassk1308
2 жыл бұрын
@@KunalKushwaha little confused, when you say pivot would be in the correct position after swaps if I have below array and I choose 4 as pivot {8,6,1,4,2,12} after swaps, ill end up having {2,4,1,6,8,12} where 4 is at index 1 but it should be at index 2 right ?
Hey , pls tell me one thing that how the primary condition is working , that break condition , that if(low>=hi) return ;
Awesome. You make everything very easy. (In your words easy peasy 😅)
Thank you so much, Kunal!
Great video kunal
Mad stuff ❤🔥❤🔥 Thanks a ton !!
Kunal bro this is a doubt. After a pass of the outer while loop, how can we confirm that pivot will end in correct index? For the array {1, 4, 2, 5, 7, 6, 3} after one pass changes to {1, 4, 2, 3, 7, 6, 5}. 5 was the chosen pivot but it does not end in correct position. The whole algorithm is correct at the end it will give the sorted array, but for this version I think we cannot confirm that after each pass pivot will end up in correct index.
@harcharansingh1997
2 жыл бұрын
Yeah bro having same doubt
@ritviksaran6199
2 жыл бұрын
@@harcharansingh1997 This method ensures that in each pass the pivot ends up in the correct index public class Main { public static void main(String[] args) { int [] arr = {1, 4, 2, 5, 7, 6, 3}; quickSort(arr, 0, arr.length - 1); for(int i : arr){ System.out.println(i); } }public static void quickSort(int [] arr, int low, int high){ if(low >= high) return; int s = low; int e = high - 1; int pivot = arr[high]; while(s pivot){ e--; } if(s
@MohamedElsayed-pb3oj
2 жыл бұрын
The reason you are having doubt is because the algorithm is incorrect. Tried it manually and tried it with the debugger and it still gave the first pass answer. Meaning the algorithm doesn't put the pivot in its intended location.
@takenbysac
2 жыл бұрын
@@MohamedElsayed-pb3oj exactly Elsayed , this algo is wrong, I tried with negative numbers as input and it failed . Tried with {2,5,3,0,8,22,9,-1,-3,-5} as input . @Kunal
@takenbysac
2 жыл бұрын
@@ritviksaran6199 even this got failed @ritvik for input as {2, 5, 3, -3, -1, -22, 0, 8, 22, 9}
brother i am not able to solve the linear recurrence relation because the function is f(n) = f(n - 1) + O(n) . When I put a^n for f(n) what to put in place for O(n). I am confuse in that part can anyone help me to understand ?
I think quick select is also a closely related technique that can be used to solve many problems.
Kunal Facing too much problem with sliding window technique. with strings and other things, it will be very helpful if you can create a video on this with solving some problems, not only the maximum sum problems but other problems also some tips or tricks will be fine. Love your work. your content really helpful.
Hey kunal please bring some leetcode sorting questions problem videos,and yes Thank you so much for this Awesome content bro ❣️
will you make video on dynamic programming as well?
Hi kunal, can you tell how long it will take for dynamic programming lecture??? Btw we are very thankful for your great work
The video explains the quicksort algorithm in detail, covering its theory, complexity, and coding implementation, while comparing it with other sorting algorithms like merge sort and discussing internal sorting functions in Java and Python. Detailed Summary for [Quick Sort Using Recursion (Theory + Complexity + Code)](kzread.info/dash/bejne/jGyn2LGqkdDHl5s.html) by [Monica](monica.im) [00:04](kzread.info/dash/bejne/jGyn2LGqkdDHl5s.html&t=4) Understanding the importance of Quicksort in sorting algorithms - Introduction to Quicksort and its significance in interviews} - Covering the complexity, time, space, code, advantages, and disadvantages of Quicksort} - Exploring internal sorting algorithms and hybrid sorting techniques} [05:15](kzread.info/dash/bejne/jGyn2LGqkdDHl5s.html&t=315.199) Explanation of quick sort using recursion - Explanation of partitioning elements based on a pivot} - Role of recursion in sorting process} - Unique aspect of pivot placement in quick sort} - Recursion's role in sorting the left and right partitions} - Selection of a new pivot element for further partitioning} [10:33](kzread.info/dash/bejne/jGyn2LGqkdDHl5s.html&t=633.44) Explanation of how to perform quick sort using recursion - Explanation of selecting the pivot element} - Identifying violations in the elements compared to the pivot} - Fixing violations by swapping elements} - Comparison and handling of elements in relation to the pivot} [15:49](kzread.info/dash/bejne/jGyn2LGqkdDHl5s.html&t=949.04) Explanation of the quick sort algorithm using recursion - Explanation of choosing the pivot and dividing the array} - Demonstration of the pivot at the correct position} - Discussion on picking the pivot element} - Introduction to complexity analysis} - Partitioning the elements based on the chosen pivot} [21:07](kzread.info/dash/bejne/jGyn2LGqkdDHl5s.html&t=1267.12) Understanding the time complexity of Quick Sort using recursion - Explaining the time taken to put the pivot at the correct position} - Discussing the recurrence relation of Quick Sort} - Analyzing the worst-case scenario in Quick Sort} - Illustrating the impact of choosing the smallest or largest pivot element} - Highlighting the consequences of the worst-case scenario in Quick Sort} [26:22](kzread.info/dash/bejne/jGyn2LGqkdDHl5s.html&t=1582.48) Explanation of time complexity and space complexity in Quick Sort - Detailed explanation of time complexity using Akra-Bazzi formula} - Importance of understanding space and time complexity in algorithms} - Best case and worst case complexity of Quick Sort} - Stability of algorithms and the concept of stable sorting} - Previous video covering sorting algorithms and stability in detail} [31:40](kzread.info/dash/bejne/jGyn2LGqkdDHl5s.html&t=1900.48) Introduction to Quick Sort Using Recursion - Starting the coding part for quick sort} - Explaining the concept of low and high indices} - Using pointers to manipulate the object in the array} [36:57](kzread.info/dash/bejne/jGyn2LGqkdDHl5s.html&t=2217.68) Explanation of quick sort using recursion and its implementation - Explanation of the recursion process in quick sort} - Dividing the array into two halves for sorting} - Initialization of low and high variables for sorting} - Discussion on different approaches to quick sort} - Recommendation to try other sorting methods before asking for help}
great video bro, thank you so much!!
An alternative approach is to swap the pivot with the last index before we start in each recursive call and then start comparing left and right. Once index cross over, we swap pivot with left pointer. Works out much cleaner at code level.
@pratheeeeeesh4839
10 ай бұрын
The approach which you told above does that calculate the pivot using the same mid concept?
@anshulgoel1940
10 ай бұрын
@@pratheeeeeesh4839 No. Pivot can be picked in any way. It won't make any difference at complexity level. This approach I suggested just keeps the code clean. Hope it helps
@36:05 you mentioned swapping doesn't happen if array already sorted. But taking {1,2,3,4,5} it does call swap with same indices.
@chennayaianjc3306
2 жыл бұрын
I think he said , swap will not happen if it is already sorted .how? in while(s
How to find the index of the pivot element by using this algorithm ?
Fabulous explanation..
why did you delete your old videos?? where do we find them now?
Hey Kunal, How did you do the DSA at your time? Like did you rely on tutorial videos or some book?
A very informative and interesting lecture 😎
This partitioning algorithm seems to be incorrect, say we take the same example provided in the video wherein the last element is always selected as the pivot - 10, 80, 30, 90, 40, 50, 70 | p = 70, s is at 10, e is at 70 now, s moves till 80 where it finds a violation (element at s should be less than 70, here it is > 70), e stays at 70 since it is also a violation(element at e should be greater than 70, here it is = 70 ), swapping happens -> array after first swap -> 10, 70, 30, 90, 40, 50, 80 -> s moves to 30, e moves to 50 notice that the new part of the array which is going to be partitioned now is 30,90,40,50 and the rest is assumed to have been placed correctly w.r.t the pivot that is 70, which is wrong as 70 is clearly not at the position where it is supposed to be.
Can someone suggest can we take mid ele as pivot
bhaiya if conditon lagana ka koi jarurat nahi tha uska binna bhi ho jata becouse loop me bhi same conddition hai or isliya if condition likhna ki koi jarurat nahi thi
The problem is I did not understand the Time and space Complexity After recurrence relation, as I am do not understand the Maths that you did, it took me more than a week to any how complete the video, but now my question is how can I do that, as I did not understand them Maths you taught, any other way to solve it ?
Hi Kunal, are you planning to launch any playlist?
My java code is not compiling at 38:21 any solution ?
Love you kunal bhai ♥️♥️
00:05 Quicksort is a crucial sorting algorithm frequently asked in interviews. 02:11 Quick sort uses pivot to divide elements into smaller and larger groups. 06:22 Quick Sort uses recursion to position the pivot element correctly after each pass. 08:20 Quick sort uses recursion to sort arrays efficiently 12:24 Understanding how to identify violations while sorting using Quick Sort. 14:35 Moving the pivot to the correct position using recursion 18:43 Picking the pivot element in quick sort 20:34 Understanding time complexity and recurrence relation in Quick Sort. 24:23 Quick sort's time complexity is O(n^2), covered in detail 26:22 Recurrence relation of merge sort explained with time complexity formulas. 29:36 Hybrid sorting algorithms combine merge sort and insertion sort for efficiency. 31:26 Exploring new approaches to solve problems is recommended. 34:59 Moving elements according to pivot and violating conditions 36:36 Explanation of the swapping process and recursion call in Quick Sort using recursion. 40:23 Quick sort is a hybrid sorting algorithm 41:58 Quick Sort using recursion is a common sorting algorithm.
Hey bhaiya, How to stay away from -ve people? and stay focused toward own goal(SDE OR DATA SCIENTIST).
Bro amazing hetric👌👌
@kunalKushwaha Bhaiya aapne to book follow krke pdhai ki hogi....to hmlog sirf is playlist ko follow krenge kya sach me utna hi knowledge gain kr paenge...kya is playlist me jitna pdhaya gya hai utna hi pdhne se sach me acchi job crack kr paenge? pls reply
Love u kunal bhaiya❤❤
Great thanks for very useful content in quite comprehensive form.
@prikshit_sharma4071
2 жыл бұрын
I Never learnt java. Should I start this course or not?🙏🏻🙏🏻
@KunalKushwaha
2 жыл бұрын
Yes
@kunal Please continue this course...
Awesooooooooooooome ❤️❤️
Thank you Kunal
this quick sort algorithm not given correct ans for (5,4,1,2,8,7,6,3) can you explain it why?
@amine_fadssi
Жыл бұрын
use variable int pivot = arr[mid] not just compare with arr[mid] directly
best videos here!
This is by far the simplest explaination of Quick Sort that i have found
best course till date in any platform
hey can you make a video about how to apply remote jobs ...
god level explain ❤️
Thank you sir
Thanks Kunal
My profssor seriously needs to learn from this dude, I was stressing about this so much, this titorial is elite. THANK YOU SO MUCH
Best explanation
Thanks a lot man
When the course will end?
loved it..
pls upload dp series soon
13:14 pivot at correct position❌every element at correct position✅
Can you please continue this course and complete it soon
Can anyone help me in understanding 24:50, How we got O(N^2). It is Linear Recurrence Relation, Right?
@Rahul-nw5rp
2 жыл бұрын
Yes man . For this you have to use substitute method . I checked common algorithms book and there was written that to use akra bazee method bi must be in range of 0 to 1 exclusive
@Sumit-lr1qj
2 жыл бұрын
Nope
@vcrohithutagonna2105
Жыл бұрын
Check out the Time and complexity video, You'll get a whole great idea
Kunal i am waiting for some other topic vedio please kindly upload it I am going to have my placement in next sem
Great teaching please make a video on heap sort as well...
@KunalKushwaha
2 жыл бұрын
Sure I will
Do a separate series for Dynamic programming bro..
Hey bro, I followed your implementation of quicksort, and the array is sorting fine, but there is a problem. Suppose there is an array [2, 4, 5, 3]. Here pivot will be the middle element at index 1 which is 4. Now, all the elements less than 4 should be on the left of 4 and greater at the right, but using your implementation. The resulting array becomes [2, 3, 5, 4]. 4 will get swapped with 3 because 4 and 3 breaks the violation. Then, start will increment and end will decrement and both point to 5. start will break the violation while end doesn't and keeps moving back until 3. Here further swapping will not take place because start > end. To note that the array becomes sorted in the next step because recursion calls quickSort on [2, 3] and [5, 4] but why didn't the 4 get placed in the right position. Is this a behaviour of quicksort or am I missing something? Please respond because this is really confusing me
@rishavraj6861
2 жыл бұрын
it works well for 2,4,5,3. it gives 2,3,4,5
@joshiomkar1394
2 жыл бұрын
@@rishavraj6861 yeah, I noticed that but it works like that only when we are using the high = n instead of n - 1.
@rishavraj6861
2 жыл бұрын
@@joshiomkar1394 how will u take high = n. n is the size of array so, for last index high = n-1. in this video high is also equals to n-1.
@nikhilsood6126
2 жыл бұрын
you are right brother......after first pass .....acc. to his theory the left of pivot must be less than pivot but it is not after first pass.......in implementation.......so it was also confusing me.......in actual acc. to his implementation only right will follow the theory not left
@ritviksaran6199
2 жыл бұрын
True, Actually you said that on the second loop, [2, 3] and [5, 4] will be passed, that is not true, [2, 3, 5] and [4] will be passed. This technique works but it does not ensure that pivot will end up in the correct index. I think he was wrong in that point.
Would u pls make a tutorial on regex
Does this work for all arrays? for example, if we take the [5,2,3,15,29,12,1] array and if we take 15 as pivot, then after following this method, I am getting [5, 2, 3, 1, 12, 29, 15] as the output in which 15 is not placed at the correct position
@yashdave4200
2 жыл бұрын
check your recursive calls, you must have made an error there which led to the answer you got
@kaustuv.chatterjee
Жыл бұрын
WAHI TOHHH
@DevanshuAugusty
Жыл бұрын
@@yashdave4200 he is saying that in one run of function only.. this quickSort method works perfectly..but it does not put pivot at the correct position in one run, you can check your self
AMAZING
Fabulous
still watching consistently 😀😀 😀😀