日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

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

發(fā)布時(shí)間:2025/4/16 c/c++ 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 用两个栈(C++)实现插入排序 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

? ?用棧實(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++)实现插入排序的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。