码迷,mamicode.com
首页 > 编程语言 > 详细

链表实现快速排序

时间:2020-01-27 15:16:35      阅读:54      评论:0      收藏:0      [点我收藏+]

标签:inf   test   default   exp   efi   value   快速   efault   return   

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

技术图片

链表实现快速排序

标签:inf   test   default   exp   efi   value   快速   efault   return   

原文地址:https://www.cnblogs.com/ygjzs/p/12235886.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!