用两个栈(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;
}

截屏:





原创粉丝点击