I want to know why we always use Sorting algorithm like (Insertion Sort or Merge Sort,…) just for lists and arrays? And why we do not use these algorithms for stack or queue?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Stacks and queues are abstract data types that have their own sense of order, i.e. LIFO (Last In First Out) for stacks and FIFO (First In First Out) for queues. As such, it does not make sense to take a queue/stack and reorder their elements around.
Wikipedia references
On Stack vs Vector
You may notice that in Java,
java.util.Stackextendsjava.util.Vector, and since it makes sense to sort aVector, perhaps it also makes sense to sort aStack. This is not the case however; the fact thatStack extends Vectoris in fact a design blunder. A stack is NOT a vector.Related questions
On using
Collections.sortonjava.util.StackDespite the fact that it doesn’t make sense to use, say, quicksort on a stack, you CAN actually use
Collections.sorton ajava.util.Stack. Why? Because, by virtue of design error (this can’t be emphasized enough!), ajava.util.Stackis ajava.util.Vector, whichimplements java.util.List, and you certainly can sort aList. Here’s an example:Note that the elements are printed in descending order: this is because of how
java.util.Stackis implemented. It pushes to and pops from the end of theVector. You don’t need to know this; you shouldn’t have known this; but these are the facts.On using an appropriate data structure
Depending on what it is that you’re trying to accomplish, a
TreeSetmay be the appropriate data structure. It is aSet, so it does not permit duplicate elements.