排序一


转自 菜鸟教程

1.插入排序
  1. 算法
  • 首先将序列的第一个元素看作有序序列,把第二个元素到最后一个元素当作未排序序列
  • 从头到尾依次扫描未排序的序列
    • 将扫描到的元素和有序序列依次从后向前比较,如果有序序列的数值较大,移动到有序序列的后一个位置
    • 直到有序序列的元素小于等于扫描到的元素,将扫描到的元素插入有序序列

例如图中元素2待排序,与前面已排序的序列相比,比2大的元素[5,15,26,27,36,38,44,47]全部向后移一位,将2插入到排序序列中。

def insertSort(arr):
	for i in range(len(arr)):
		preIndex = i-1
		current = arr[i]
		while preIndex >0 and arr[preIndex] > current:
			current[preIndex+1] = current[preIndex]
			preIndex -= 1
		arr[preIndex+1] = current
	return arr
2. 堆排序

刷题的时候遇见很多前k项、第k项之类的,用的都是最大堆、最小堆,所以还是先写一下最大堆、最小堆的部分实现

最小堆
class MinHeap(object):
    def __init__(self, size):
        self.heap = []
        self.size = size

	#插入元素
    def add_min_heap(self, item):
        if self.get_size() == self.size:
            print("当前堆已满")
       
        #首先在顶端插入当前值,再进行调整
        self.heap.insert(0, item)
        heap_len = self.get_size()
        #如果这是唯一一个元素,直接返回
        if heap_len == 1:
            return
		#否则调整当前堆
        current_index = 0
		heapify(current_index )
		
	#调整堆
	def heapify(current_index ):
		min_index = current_index
		#左子节点
        left_index = current_index*2 + 1
        #右子节点
        right_index = (current_index+1) * 2
         heap_len = self.get_size()
        if right_index < heap_len and self.heap[left_index ] < self.heap[current_index]:
        	min_index = left_index 
        if right_index  < heap_len and self.heap[right_index ] < self.heap[min_index]:
        	min_index = right_index 
        if min_index != current_index:
        	self.swap(current_index, min_index)
        	heapify(min_index)
    
	#两个元素互换位置
    def swap(self, target_index, current_index):
        self.heap[target_index],self.heap[current_index] = self.heap[current_index],self.heap[target_index]

	#父元素
    def get_father_index(self, current_index):
        if current_index % 2 != 0:
            father_index = current_index // 2
        else:
            father_index = (current_index - 1)//2
        return father_index

    def get_size(self):
        return len(self.heap)
        
	#最小值
    def peek(self):
        return self.heap[0]
最大堆
class MaxHeap():
	    def __init__(self, size):
	        self.heap = []
	        self.size = size
        
        #由列表创建最大堆
        def buildMaxHeap(arr):
        	self.heap = arr
        	self.size = len(arr)
        	#从倒数第一个有子节点的子堆开始,从右底端调整堆
        	for i in range(len(arr)//2,-1,-1):
        		heapify(i)
        	
        #调整堆
        def heapify(current_index ):
			max_index = current_index
	        left_index = current_index*2 + 1
	        right_index = (current_index+1) * 2
	        heap_len = self.get_size()
	        if left_index  <heap_len and self.heap[left_index  ] > self.heap[current_index]:
	        	max_index = left_index  
	        if right_index  < heap_len and self.heap[right_index ] > self.heap[min_index]:
	        	max_index = right_index 
	        if max_index != current_index:
	        	self.swap(current_index, max_index )
	        	heapify(max_index )
	    
		#两个元素互换位置
    	def swap(self, target_index, current_index):
        	self.heap[target_index],self.heap[current_index] = self.heap[current_index],self.heap[target_index]
        	
        def get_size(self):
        	return len(self.heap)
堆排序

算法:

  • 用已有列表创建一个大顶堆
  • 把堆顶和堆尾的元素互换
  • 把堆的尺寸缩小1,调整当前堆顶元素的位置,使之称为新的大顶堆
  • 重复,直至堆的尺寸为1
    优点:当待排序的数组占用内存非常大时,不用多占用内存。O(nlogn)
#换位置
def swap(arr, i, j):
    arr[i], arr[j] = arr[j], arr[i]
#调整最大值位置
def heapify(arr, i):
    left = 2*i+1
    right = 2*i+2
    largest = i
    if left < arrLen and arr[left] > arr[largest]:
        largest = left
    if right < arrLen and arr[right] > arr[largest]:
        largest = right

    if largest != i:
        swap(arr, i, largest)
        heapify(arr, largest)

#利用原始数组,创建堆
def buildMaxHeap(arr):
    import math
    #在《树 三》有关最大堆创建中涉及,先调整最底层最右侧的堆,
    #逐渐向左上调整,最后就变成了最大堆结构
    for i in range(math.floor(len(arr)/2),-1,-1):
        heapify(arr,i)
#排序
def heapSort(arr):
    global arrLen
    #堆的当前尺寸
    arrLen = len(arr)
    #创建堆
    buildMaxHeap(arr)
    for i in range(len(arr)-1,0,-1):
    	#把堆顶和堆尾交换位置
        swap(arr,0,i)
        #并且堆的尺寸减少1
        arrLen -=1
        #重新调整堆
        heapify(arr, 0)
    return arr
3. 计数排序

如果列表是n个0-k之间的整数,运行时间是O(n+k);只适合数据范围[0,100]之间的小范围列表,因为他需要开辟数据范围长度的内存。
算法“:

  • 找出待排序数组中的最大值、最小值
  • 统计数组中每个元素出现的次数,存入数组中
  • 反向填充目标数组

def countingSort(arr, maxValue):
    bucketLen = maxValue+1
    bucket = [0]*bucketLen
    sortedIndex =0
    arrLen = len(arr)
    for i in range(arrLen):
        if not bucket[arr[i]]:
            bucket[arr[i]]=0
        bucket[arr[i]]+=1
    for j in range(bucketLen):
        while bucket[j]>0:
            arr[sortedIndex] = j
            sortedIndex+=1
            bucket[j]-=1
    return arr
4. 桶排序

利用函数的映射关系,把元素放到不同的桶中,在桶中进行排序,然后取出

#桶排序
def bucketsort(arr, bucketsize=5):
    if len(arr) == 0:
        return arr
    minvalue = min(arr)
    maxvalue = max(arr)
    
    #初始化桶
    bucketcount = (maxvalue - minvalue)//bucketsize + 1
    buckets = [None]*bucketcount
    for i in range(bucketcount):
        buckets[i] = []

    #将数据映射到桶中
    for i in arr:
        buckets[(i-minvalue)//bucketsize].append(i)
    
    arrReturn = []
    #对每个桶进行排序
    for i in buckets:
    	#调用了插入排序
        insertsort(i)
        arrReturn.extend(i)
    return arrReturn
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值