原文:
Write a program to sort a stack in ascending order. You should not make any assumptions about how the stack is implemented. The following are the only functions that should be used to write this program: push | pop | peek | isEmpty.
译文:
写程序将一个栈按升序排序。对这个栈是如何实现的,你不应该做任何特殊的假设。 程序中能用到的栈操作有:push | pop | peek | isEmpty。
至少有四种方法:
1)借助另一个栈来排序:
另一个栈(有序栈)装排序完(从大到小)的结果。如何把无序栈的元素添加到有序栈呢?我们可以把下一个待插入的元素存放在一个临时变量toInsert里,然后在有序栈里,把所有比toInsert大的都倒腾到无序栈内。这样保证当toInsert插入有序栈时,toInsert以下的所有元素都小于它。然后继续处理下一个无序栈栈顶元素,最后直到无序栈中的所有元素都被转移到有序栈中!Time: O(N^2), Space: O(N)
2)如果可以用heap/priority queue,则就太简单了。
3) 可以在栈上进行merge sort。把当前栈的元素分到左右两个子栈,然后分别对两个子栈排序。最后是merge过程。不过要注意:栈只能从栈顶取元素,而左右栈已经是按从大到小排序好,所以要取出较大的元素压入stack,这样stack会变成从小到大排序,因此在merge的最后需要reverse stack!
4) 还可以在栈上进行quick sort。原理同merge sort
package Stack_Queue;
import java.util.Stack;
import CtCILibrary.AssortedMethods;
public class S3_6 {
// 输入一个乱序的栈,返回一个排序过(栈顶最大,栈底最小)的栈
// Time: O(N^2), Space: O(N)
public static Stack<Integer> sort(Stack<Integer> stack) {
Stack<Integer> sorted = new Stack<Integer>();
while( !stack.isEmpty() ) {
int toInsert = stack.pop(); // 先保存待处理的元素到一个临时变量
while( !sorted.isEmpty() && sorted.peek() > toInsert ) { // 把比toInsert大的元素都倒腾到stack
stack.push(sorted.pop());
}
sorted.push(toInsert); // 现在sorted栈顶元素已经小于toInsert,可以直接插入了
}
return sorted;
}
// mergeSort
// Time: O(NlogN), Space: O(N)
public static Stack<Integer> mergeSort(Stack<Integer> stack) {
if ( stack.size() <= 1) {
return stack;
}
Stack<Integer> left = new Stack<Integer>();
Stack<Integer> right = new Stack<Integer>();
int count = 0;
while (stack.size() != 0) {
count++;
if (count % 2 == 0) {
left.push(stack.pop());
} else {
right.push(stack.pop());
}
}
left = mergeSort(left);
right = mergeSort(right);
// merge合并过程
while ( left.size()>0 || right.size()>0 ) {
if ( left.size() == 0 ) { // 左栈为空,把右栈全部添加到stack
stack.push(right.pop());
} else if ( right.size() == 0 ) { // 右栈为空为空,把左栈全部添加到stack
stack.push( left.pop() );
}
// 注意到栈只能从栈顶取元素,而左右栈已经是按从大到小排序好
// 所以要取出较大的元素压入stack,这样stack会变成从小到大排序,
// 因此在merge的最后需要reverse stack
else if ( right.peek().compareTo(left.peek()) <= 0 ) {
stack.push(left.pop());
} else {
stack.push(right.pop());
}
}
Stack<Integer> reveseStack = new Stack<Integer>();
while (stack.size() > 0 ) {
reveseStack.push(stack.pop());
}
return reveseStack;
}
public static void main(String [] args) {
Stack<Integer> s = new Stack<Integer>();
for (int k = 1; k < 5; k++) {
int r = AssortedMethods.randomIntInRange(0, 1000);
s.push(r);
}
// s = sort(s);
s = mergeSort(s);
int last = Integer.MAX_VALUE;
while(!s.isEmpty()) {
int curr = s.pop();
System.out.println(curr);
if (curr > last) {
System.out.println("Error: " + last + " " + curr);
}
last = curr;
}
}
}
分享到:
相关推荐
【完整源码列表】 chapter_01_Introduction chapter_03_Linear_List chapter_04_String chapter_05_Stack_and_Queue chapter_06_Binary_tree chapter_07_Graph chapter_08_Dict_and_Set chapter_09_Sort
23.4 堆排序sort_heap 351 23.5 是否为堆is_heap 352 23.6 局部排序partial_sort 354 23.7 局部排序复制partial_sort_copy 356 23.8 排序sort 359 23.9 归并merge 366 23.10 内部归并inplace_merge ...
23.4 堆排序sort_heap 351 23.5 是否为堆is_heap 352 23.6 局部排序partial_sort 354 23.7 局部排序复制partial_sort_copy 356 23.8 排序sort 359 23.9 归并merge 366 23.10 内部归并inplace_merge ...
23.4 堆排序sort_heap 351 23.5 是否为堆is_heap 352 23.6 局部排序partial_sort 354 23.7 局部排序复制partial_sort_copy 356 23.8 排序sort 359 23.9 归并merge 366 23.10 内部归并inplace_merge ...
├─array_stack_queue ├─binarysearchtree ├─linkedlist ├─matrix ├─search ├─sort └─util 排序 方式 算法 时间复杂度 空间复杂度 稳定性 数据排序情况 交换 冒泡排序 O(n^2) O(1) 稳定 无关 随机快排 ...
With a strong emphasis on structured design and programming techniques, it features precise instructions on all the steps involved in data structure development-from theoretical conception to ...
leetcode伪代码 my-demo Algorithm 我的算法学习相关记录 排序 Sort 根据算法导论(中文版第四版...Stack,Queue,Dump 贪心算法 GreedyAlgorithm 递归、回溯、分治 Recursive,Backtrack,Devide and Conquer flink 反馈流
你将看到各种算法(排序、搜寻、排列组合、数据移动与复制…)的实现;你甚至将看到底层的memory pool 和高阶抽象的traits 机制的实现。那些数据结构、那些算法、那些重要观念、那些编程实务中最重要最根本的珍宝,...
免费,分上下两部分,上部分内容包括Union-Find, basic data structures(Array, LinkedList, Queue, Stack, prioprity queue, symbol table...), sorting algorithms (selection sort, insertion sort, shell sort, ...
庖丁解牛(侯捷自序) i ...附录a 参考资料与推荐读物(bibliography) 461 附录b 侯捷网站简介 471 附录c stlport 的移植经验(by 孟岩) 473 borland c++builder 5 474 microsoft visual c++ 6.0 477 索引 481
一、stack 堆栈 5 成员函数: 5 实例程序: 5 二、queue 队列 6 成员函数: 6 实例程序: 6 三、Priority Queues 优先队列 7 成员函数: 7 实例程序: 7 四、Bitset位集合 9 成员函数: 9 实例程序: 9 五、list ...
栈(Stack) 队列(Queue) 链表(Linked List) 树(Tree) 堆(Heap) 字典(Dictionary) 哈希表(Hash Table) 图(Graph) 3. 基本算法思维 枚举 递归 回溯 分治 贪心算法 试探算法 模拟算法 动态规划 分支限界...
arg.c choucha.c factorial.c leapyear.c ptr_func.c stack.c test-sd.c big_data.c circular_size.c factorial_enhance.c max_common.c ptr_test.c str_tok.c tree.c big_mult.c count.c find.c mystr.c queue.c ...
sort里面是几种排序方法:冒泡排序、插入排序、选择排序、希尔排序 recursion recursion里面是递归的案例,迷宫回溯、一些递归测试、八皇后问题 dac 分治算法里面是汉诺塔问题 dynamic dynamic背包问题 search ...
Stack 栈 Queue 队列 Linked List 链表 Binary Search Tree 二分搜索树 Heap 堆 Index Heap 索引堆 Segment Tree 线段树 Trie Union Find 并查集 AVL Red Black Tree 红黑树 Hash Table 哈希表 Graph 图论基础 ** ...
Stack Binary Heap Fibonacci Heap Priority Queue (list based) Bubble sort Selection sort Insertion sort Radix sort Quick sort Merge sort Heap sort Double linked list Skip list Self-organized linked-...
第四、五周(InsertionSort、QuickSort) 第六周(Heap Sort) 第七周(Merge Sort) 第八周(Set Mismatch) 第九周(无新进度) 第十周(BST) 第十一周(Hash Table) 第十二、十三周(DFS(Stack) & BFS(Queue)) 第十四、十五周...
Find out about Swift generators and sequences, and see how to use them to implement advanced data structures such as Stack, StackList, Queue, and LinkedList Implement sorting algorithms such as ...
selectsort 选择排序 insertsort 插入排序 quicksort 快速排序 mergeSort 归并排序 stack 栈 leetCode maximumProduct 628. 三个数的最大乘积 numEquivDominoPairs 1128. 等价多米诺骨牌对的数量 pivotIndex 724. ...
and see how to use them to implement advanced data structures such as Stack, StackList, Queue, and LinkedList Implement sorting algorithms such as Insertion Sort, Merge Sort, and Quick Sort and ...