About Sorting Algorithms Applied to Stacks and Queues

I want to know why we always use a type sorting algorithm (Insert Sort or Sort Sort, ...) for lists and arrays only? And why don't we use these algorithms for a stack or queue?

+3
source share
6 answers

Stacks and queues are abstract data types that have their own sense of order, that is, LIFO (Last In First Out) for stacks and FIFO (First In First Out) for queues. Thus, it makes no sense to accept a queue / stack and reorder their elements.

Wikipedia links


On stack vs vector

, Java java.util.Stack extends java.util.Vector, a Vector, , a Stack. ; , Stack extends Vector . .


Collections.sort java.util.Stack

, , , quicksort , CAN Collections.sort java.util.Stack. ? ( !), java.util.Stack - java.util.Vector, implements java.util.List, , , List. :

    Stack<Integer> stack = new Stack<Integer>();
    stack.push(1);
    stack.push(3);
    stack.push(5);
    stack.push(2);
    stack.push(4);

    Collections.sort(stack); // by virtue of design error!!!

    System.out.println(stack); // prints "[1, 2, 3, 4, 5]"
    while (!stack.isEmpty()) {
        System.out.println(stack.pop());
    } // prints "5", "4", "3", "2", "1"

, : - java.util.Stack. Vector. ; ; .


, , TreeSet . Set, .

    NavigableSet<Integer> nums = new TreeSet<Integer>();
    nums.add(5);
    nums.add(3);
    nums.add(1);
    nums.add(2);
    nums.add(6);

    System.out.println(nums.pollFirst()); // prints "1"
    System.out.println(nums.pollFirst()); // prints "2"
    nums.add(4);
    System.out.println(nums.pollFirst()); // prints "3"
    System.out.println(nums.pollFirst()); // prints "4"
+13

, . , .

+5

, . : PriorityQueue, .

+3

, . , .

+2

. - , Last In First Out (LIFO). Stack, LIFO. , 7, 3, 5, 4 . , . , pop(), 4. , . 3, 4, 5, 7, pop(), 7, , . LIFO.

Queue, First in First Out. - , , .

+1

, Stack Queues , . , , , .

- , , .

0

Source: https://habr.com/ru/post/1749733/


All Articles