快速排序的单链表版本

快速排序单链表版本

基本过程:

  1. 用两个指针i, j分别指向第一和第二个节点
  2. 比较j所指向的元素和链表第一个节点的值(作为基轴)的大小,
    如果j指向的元素较小,则j ++
    否则(1)i ++;(2)swap(i,j);j ++
  3. 重复步骤2,知道超出范围。
  4. 将基准元素和i指向的位置,交换,则I所在的位置已经排好了
  5. 递归左边一半sort(left, i)
  6. 递归右边一半sort(i + 1, end)

可以看到,基本思想是,i右边的元素,都是大于基轴的,j往后扫描,一旦发现小于基轴的元素,则和i的下一个元素交换,将较小的元素换到左边。一轮结束后,i指向的元素值小于基轴的,所以和基轴交换。然后递归完成左右半部分。
代码如下:

#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
class Node(object):
  def __init__(self):
    self.value = None
    self.next = None
    
def swapNode(x, y):
  if x == y:
    return
  tmp = x.value
  x.value = y.value
  y.value = tmp
  
def swapArray(nums, x, y):
  if x == y:
    return
  tmp = nums[x]
  nums[x] = nums[y]
  nums[y] = tmp
  
def quick_sort(head, end):
  if head is None or head == end:
    return

  left = head
  right = head.next
  while right != end:
    if right.value < head.value :
      left = left.next
      swapNode(left, right)
    right = right.next

  swapNode(head, left)
  quick_sort(head, left)
  quick_sort(left.next, end)

def quick_sort_array(nums, start, end):
  if start >= end:
    return
  low = start
  high = start + 1
  while high < end:
    if nums[low] > nums[high]:
      low += 1
      swapArray(nums, low, high)
    high += 1
  swapArray(nums, low, start)
  quick_sort_array(nums, start, low)
  quick_sort_array(nums, low + 1, end)

def printLinkList(head):
  p = head.next
  while p is not None:
    print p.value, "->",
    p = p.next
  print

def printArray(nums):
  for x in nums:
    print x, "->" ,
  print

def main():
  nums = [3, 7, 2, 1, 6, 0, 5]
  head = Node()
  p = head
  for x in nums:
    s = Node()
    s.value = x

    p.next = s
    p = p.next
  printLinkList(head)

  quick_sort(head.next, None)
  printLinkList(head)

  printArray(nums)
  quick_sort_array(nums, 0, len(nums))
  printArray(nums)

if __name__ == "__main__":
  main()

你可能感兴趣的:(排序)