用两个栈(C++)实现插入排序
来源:互联网 发布:maven 打包 java文件 编辑:程序博客网 时间:2024/06/10 00:58
用栈实现插入排序时,我们先将存放该数据的栈排序到另一个栈中,最后在将另外一个栈的内容倒放到当前栈中。图如下:
实现:
#pragma once
template <typename E> class AStack {
private:
int maxSize; // Maximum size of stack
int top; // Index for top element
E *listArray; // Array holding stack elements
public:
AStack(int size = 20) // Constructor
{
maxSize = size; top = 0; listArray = new E[size];
}
~AStack() { delete[] listArray; } // Destructor
void clear() { top = 0; } // Reinitialize
void push(const E& it) { // Put "it" on stack
listArray[top++] = it;
}
E pop() { // Pop top element
return listArray[--top];
}
const E& topValue() const { // Return top element
return listArray[top - 1];
}
int length() const { return top; } // Return length
void insertSort()
{
AStack<int>L1;
while (length()>0) //when this is empty,circle break.
{
E element = pop();
int count = 0; // to record how many element in this stack, which has been pushed into.
if (L1.length() == 0) //if L1 is empty, push element into 12.
{
L1.push(element);
}
else
{
if (element > L1.topValue())
L1.push(element);
else
{
while (element < L1.topValue()&&L1.length()!=0)
{
push(L1.pop()); //make L1's elements into the current stack when they are minor to the element.
count++;
}
L1.push(element);
while (count != 0)
{
L1.push(pop());
count--;
}
}
}
}
for (int i = 0; L1.length() > 0; i++)
push(L1.pop());
}
};
main函数:
#include"AStack.h"
#include<iostream>
using namespace std;
int main()
{
AStack<int>L1;
L1.push(2);
L1.push(1);
L1.push(9);
L1.push(5);
L1.push(7);
L1.push(11);
L1.push(35);
L1.push(0);
L1.insertSort();
while (L1.length() > 0)
cout << L1.pop() << endl;
}
截屏:
- 用两个栈(C++)实现插入排序
- 插入排序C实现
- C实现插入排序
- 插入排序 C实现
- 用C语言实现插入排序
- 用c语言实现插入排序
- 插入排序C语言实现
- C/C++实现插入排序
- 插入排序的c实现
- 插入排序c语言实现
- 插入排序C语言实现
- 插入排序C语言实现
- 插入排序(C语言实现)
- 插入排序(C实现)
- 插入排序C语言实现
- 插入排序C语言实现
- c语言实现插入排序
- c语言实现插入排序
- http响应码304详解
- Hadoop 使用 Python 来写 map-reduce
- Python(五) 条件语句和循环语句
- Android 蓝牙开发(二)Ble 开发(android4.3)
- 作为background-image的图片路径中图片名带括号后不显示
- 用两个栈(C++)实现插入排序
- 查询在一张表不在另外一张表的记录
- 正则
- UiAutomator python+uiautomator 自动义测试框架
- 工具查看
- post请求传xml参数(KissXML 生成xml文件)
- 一年过去了,这家网站的流量竟然达到……
- WorkerMan::Worker类解析(4)
- 【codevs 2913】建筑抢修