用两个栈(C++)实现插入排序
? ?用棧實(shí)現(xiàn)插入排序時(shí),我們先將存放該數(shù)據(jù)的棧排序到另一個(gè)棧中,最后在將另外一個(gè)棧的內(nèi)容倒放到當(dāng)前棧中。圖如下:
實(shí)現(xiàn):
#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函數(shù):
#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;
}
截屏:
總結(jié)
以上是生活随笔為你收集整理的用两个栈(C++)实现插入排序的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为自带浏览器绕坑大法!
- 下一篇: 自组织线性表