快速排序链表

时间复杂度O(N*logN),空间复杂度O(1)

参考 http://www.cnblogs.com/TenosDoIt/p/3666585.html


//依据快速排序METOHD_3的思想
//取第一个元素作为枢纽元
//链表范围是[low, high)

#include <iostream>
using namespace std;

struct ListNode {
  int val;
  ListNode *next;
  ListNode(int x) : val(x), next(NULL) {}
};

void swap(int &a, int &b){
  int tmp = a;
  a = b;
  b = tmp;
}

ListNode *partition(ListNode *head, ListNode *tail){
  //链表范围是[low, high)
  ListNode *mid = head;
  for (ListNode *p = head->next; p != tail; p = p->next){
    if (p->val < head->val){
      mid = mid->next;
      if (mid != p){
        swap(mid->val, p->val);
      }
    }
  }
  swap(mid->val, head->val);

  return mid;
}

void quick_sort(ListNode *head, ListNode *tail){
  //链表范围是[low, high)
  if (head == tail || head->next == tail)
    return;

  ListNode *mid = partition(head, tail);
  quick_sort(head, mid);
  quick_sort(mid->next, tail);
}

ListNode *quick_sort_list(ListNode *head){
  //链表范围是[low, high)
  if (head == NULL || head->next == NULL)
    return head;

  quick_sort(head, NULL);
  
  return head;
}

int main(){
  ListNode *head = new ListNode(0);
  ListNode *node1 = new ListNode(3);
  ListNode *node2 = new ListNode(1);
  ListNode *node3 = new ListNode(2);
  ListNode *node4 = new ListNode(6);
  ListNode *node5 = new ListNode(5);
  ListNode *node6 = new ListNode(4);

  head->next = node1;
  node1->next = node2;
  node2->next = node3;
  node3->next = node4;
  node4->next = node5;
  node5->next = node6;
  ListNode *p = head;
  while(p){
    cout << p->val << '\t';
    p = p->next;
  }
  cout << endl;

  ListNode *result = quick_sort_list(head);

  p = result;
  while(p){
    cout << p->val << '\t';
    p = p->next;
  }
  cout << endl;

  int ttt = 0;
  return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值