单链表之快速排序

来源:互联网 发布:手机刷机救砖软件 编辑:程序博客网 时间:2024/06/03 15:12

快速排序的时间复杂度为O(n logn)。

快排依次把每个区间的第一个元素放在“合适”的位置,这个位置的特征是左边元素都比它小,右边都不小于它。

再用这个元素划分区间,直到区间不能划分。

这种思路适用递归。

先上一个数组的快排

#include <iostream>using namespace std;int quickSort(int  *a,int left,int right){if(left<right){int i=left;int j=right;int temp=a[i];while(true){while(i<j&&a[j]>=temp){j--;}a[i]=a[j];while(i<j&&a[i]<temp){i++;}a[j]=a[i];if(i==j){a[i]=temp;break;}}quickSort(a,left,i-1);quickSort(a,i+1,right); }}int main(int argc, char** argv) {int a[]={0,1,2,3,2,5,6,4,8,13};int n=sizeof(a)/sizeof(int);quickSort(a,0,n-1);int i=0;for(;i<n;i++){cout<<a[i]<<" ";}return 0;}
************************************************************************************************

常见的笔试题目中有用单链表实现快速排序。

我们知道,单链表不能随机取值,若还用上述方法,每次取j--的时候,从头节点开始找,太耗费时间了。

这里采取一种交换的策略,用两个指针slow、fast来确定位置。用fast从[start+1 , end]找比start-val小的元素,找到一个就插入slow的下一个位置,fast到end之后,交换start和slow的位置即可,这样一趟下来,就确定了左边小于上一趟start->val,右边不小于上一趟start->val了。

#include<iostream>#include<algorithm>using namespace std;class ListNode {public:    int val;    ListNode *next;    ListNode(int val) {        this->val = val;        this->next = NULL;}};void print_node(ListNode *head,ListNode *end){//输出链表 while(head!=end){cout<<head->val<<" ";head=head->next;}cout<<endl;}   void quickSort(ListNode *start,ListNode *end) {    // write your code here    if(start==end) return ;ListNode *slow=start;    ListNode *fast=start->next;    int k=start->val;    while(fast!=end){    if(fast->val < k){    swap(slow->next->val,fast->val);    slow=slow->next;}fast=fast->next;}swap(slow->val,start->val);print_node(start,end);quickSort(start,slow);quickSort(slow->next,end);}  int main() {int a[]={4,8,2,3,2,5,6,4,8,13,10};ListNode *l1,*p;l1=new ListNode(a[0]);p=l1;for(int i=1;i<(sizeof(a)/sizeof(int));i++){ListNode *temp=new ListNode(a[i]);p->next=temp;p=p->next;}quickSort(l1,NULL);print_node(l1,NULL);}  



0 0
原创粉丝点击