Stack-and queue-based sorting algorithms in Java

Source: Internet
Author: User

Topic 1: Use a secondary stack and some additional non-array variables to store the elements in the stack s in ascending order.

Topic 2: Use a secondary queue and some additional non-array variables to store the elements in queue Q in ascending order.

1. Java implementation, the first use of linked list LinkedList structure stack data structure.

import java.util.LinkedList;
public class IntStack {
   private LinkedList<Integer> storage = new LinkedList<Integer> ();
   /** 入栈 */
   public void push(int v) {
     storage.addFirst(v);
   }
   /** 出栈,但不删除 */
   public int peek() {
     return storage.getFirst();
   }
   /** 出栈 */
   public int pop() {
     return storage.removeFirst();
   }
   /** 栈是否为空 */
   public boolean empty() {
     return storage.isEmpty();
   }
   /** 打印栈元素 */
   public String toString() {
     return storage.toString();
   }
}

2. Use two stacks for sorting operations.

2.1 Method Init (int[] ints, IntStack stack) deposit data into stack 1;

2.2 Method Sort (), the main algorithm is:

[1]sizeone and Sizetwo record the number of data to be sorted in the current two stacks;

[2] do the loop until the number of data to be sorted in a stack is 1, which indicates that the order is complete;

[3] The process of sorting is,

[3.1] First out of the stack 1 from the unsorted data, find the largest, stored in Max, and the rest into the stack 2;

[3.2] At this time the largest person of the data was found;

[3.3] Again, from the stack 2 in order to take out the unsorted data, find the largest, deposit max, and the rest into the stack 1;

[3.4] At this time already found the second largest of the data;

[3.5] alternating and reciprocating sequentially until the termination condition is satisfied [2];

[3.6] At this time Sizeone and Sizetow of the inevitable one is 0, one is 1;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.