Sort With 3 Stacks - Medium

三栈排序算法
本文介绍了一种使用三个栈进行排序的算法,通过不断倒换元素并寻找全局最小值实现排序,时间复杂度为O(n^2)。同时,还探讨了使用归并排序改进算法,达到O(nlogn)的时间复杂度。

Given one stack with integers, sort it with two additional stacks (total 3 stacks). 

After sorting the original stack should contain the sorted integers and from top to bottom the integers are sorted in ascending order.

Assumptions:

  • The given stack is not null.

Requirements:

  • No additional memory, time complexity = O(nlog(n)).

 

M1: 普通作法,来回倒,s2作为buffer,s3作为output,最后再把s3中排完序的数字倒入s1

time: O(n^2), space: O(n)

public class Solution {
  public void sort(LinkedList<Integer> s1) {
    LinkedList<Integer> s2 = new LinkedList<Integer>();
    LinkedList<Integer> s3 = new LinkedList<Integer>();
    // Write your solution here.
    if(s1 == null) {
      return;
    }
    
    while(!s1.isEmpty() || !s2.isEmpty()) {
      int globalMin = Integer.MAX_VALUE;
      while(!s1.isEmpty()) {
        int tmp = s1.pop();
        globalMin = tmp < globalMin ? tmp : globalMin;
        s2.push(tmp);
      }
      while(!s2.isEmpty()) {
        int tmp = s2.pop();
        if(tmp != globalMin) {
          s1.push(tmp);
        } else {
          s3.push(globalMin);
        }
      }
    }
    
    while(!s3.isEmpty()) {
      s1.push(s3.pop());
    }
  }
}

 

M2: merge sort

time: O(nlogn), space: O()

转载于:https://www.cnblogs.com/fatttcat/p/10216064.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值