链表实现快速排序

六月ゝ 毕业季﹏ 提交于 2020-01-27 15:15:32

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])
})

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!