您的位置:首页 > 编程语言 > C语言/C++

用两个栈(C++)实现插入排序

2017-10-17 16:46 435 查看
   用栈实现插入排序时,我们先将存放该数据的栈排序到另一个栈中,最后在将另外一个栈的内容倒放到当前栈中。图如下:

实现:

#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;

}

截屏:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息