Reputation: 3
I'm new to algorithms so I'm trying to understand every possible situtation. Last thing I did was to work with QuickSort algorithm sorting integers with a single pivot. My question is: What happens when I have to sort an array with only two integers? For example the arr[2]={4,2}
. I know that the algorithm works but I'm not sure about how it makes it happen. I didn't found any animation for just 2 numbers, so please can anyone explain me what happens step by step in this situation?
Thanks a lot! Also, I'm sorry if its a foolish question but I can't figure it out. Have a nice day guys!
Upvotes: 0
Views: 532
Reputation: 3116
You perform the sorting with two elements as with any generic list size:
4
.4 < 4
is false. Right hand list.2 < 4
is true. Left hand list.{2}
is sorted already{4}
is sorted already{2, 4}
Upvotes: 0
Reputation: 83577
The answer depends on your base case. In many academic implementations, the base cases are an empty array or an array with one element. This means that an array with two elements is treated the same way an array with 1000 elements: pick a pivot, divide the array into two subarrays, then make a recursive call on the two subarrays.
Alternatively, you can treat an array of 2 elements as a base case and sort it directly.
Upvotes: 0