链表实现快速排序
Posted ygjzs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表实现快速排序相关的知识,希望对你有一定的参考价值。
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])
})
以上是关于链表实现快速排序的主要内容,如果未能解决你的问题,请参考以下文章