欢迎来到 跌倒的小黄瓜 的博客

♪(^∇^*)我要当大佬,(#^.^#)哈哈哈哈,(。-ω-)zzz我要成为优秀的人,(*^▽^*)٩(๑>◡<๑)۶O(∩_∩)O哈哈~~~~~~~~欢迎━(*`∀´*)ノ亻!

链表实现快速排序

javascript中实现一个链表的快速排序

class Node {
  constructor (value) {
    this.val = value
    this.next = undefined
  }
}

class NodeList {
  constructor (arr) {
    let head = new Node(arr.shift())
    let next = head
    arr.forEach(item => {
      next.next = new Node(item)
      next = next.next
    })
    return head
  }
}

let swap = (p, q) => {
  let val = p.val
  p.val = q.val
  q.val = val
}

let partion = (begin, end) => {
  let val = begin.val
  let p = begin
  let q = begin.next
  while (q !== end) {
    if (q.val < val) {
      p = p.next
      swap(p, q)
    }
    q = q.next
  }
  // 让基准元素跑到中间去
  swap(p, begin)
  return p
}

export default function sort (begin, end) {
  if (begin !== end) {
    let part = partion(begin, end)
    sort(begin, part)
    sort(part.next, end)
  }
}

export {
  Node,
  NodeList
}


测试文件

import sort, {
  NodeList
} from '../../code/chain/lesson1'

test('sort:1', () => {
  let head = new NodeList([4, 1, 3, 2, 7, 9, 10, 12, 6])
  sort(head)
  let res = []
  let next = head
  while (next) {
    res.push(next.val)
    next = next.next
  }
  expect(res).toEqual([1, 2, 3, 4, 6, 7, 9, 10, 12])
})

posted @ 2020-01-27 13:55  跌倒的小黄瓜  阅读(319)  评论(0编辑  收藏  举报