链表排序
class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next
简单排序算法
1.插入排序,时间复杂度O(N^2),空间复杂度O(1)
针对一个已排序序列,将元素插入某位,后续元素后移
class Solution: """ @param: head: The head of linked list. @return: You should return the head of the sorted linked list, using constant space complexity. """ def sortList(self, head): # write your code here if head is None or head.next is None: return head crt = head.next while crt is not None: x = crt.val p = head while p != crt and p.val <= x: p = p.next while p != crt: y = p.val p.val = x p = p.next x = y crt.val = x crt = crt.next return head
2.选择排序,时间复杂度O(n^2),空间复杂度O(1)
按递增方式选出元素,按顺序排放即可
3.交换排序
一个序列没排好序,那么其中一定有逆序存在,不断减少逆序对,则最终得到排序序列
冒泡排序:每一次扫描把最大元素移到序列最后,经过n-1次扫描,一定能完成排序
快速排序
选择一种标准,把被排序序列中的记录按标准分为大小两组。采用同样方式递归划分。下面针对顺序表实现
def qsort_res(lst, l, r): if l >= r: return i, j = l, r pivot = lst[i] while i < j: while i < j and lst[j] >= pivot: j -= 1 if i < j: lst[i] = lst[j] i += 1 while i < j and lst[i] >= pivot: i += 1 if i < j: lst[j] = lst[i] j -= 1 lst[i] = pivot qsort_res(lst, l, i-1) qsort_res(lst, i+1 ,r)
def qsort_2(lst,begin,end): if begin >= end: return pivot = lst[begin] i = begin for j in range(begin + 1, end + 1): if lst[j] < pivot: i += 1 lst[i], lst[j] = lst[j], lst[i] lst[begin],lst[i] = lst[i], lst[begin] qsort_2(lst,begin, i - 1) qsort_2(lst,i+1 , end)
归并排序
用快慢指针将链表一分为二
class Solution: """ @param: head: The head of linked list. @return: You should return the head of the sorted linked list, using constant space complexity. """ def sortList(self, head): # write your code here if head is None or head.next is None: return head pfast = head pslow = head while pfast.next != None and pfast.next.next != None: pfast = pfast.next.next pslow = pslow.next pfast = pslow.next pslow.next = None list1 = self.sortList(head) list2 = self.sortList(pfast) sorted = self.mergeTwoLists(list1,list2) return sorted def mergeTwoLists(self, l1, l2): ans = ListNode(0) tmp = ans while l1 != None and l2 != None: if l1.val < l2.val: tmp.next = ListNode(l1.val) l1 = l1.next tmp = tmp.next else: tmp.next = ListNode(l2.val) l2 = l2.next tmp = tmp.next if l1 == None: tmp.next = l2 else: tmp.next = l1 return ans.next