堆排序python实现,迭代子列表堆排序python实现

I've found different versions of heap sort for python, but I can't seem to find the one that matches my needs.

Iterative Heap Sort is the closest I found,

but I can't quite figure out how to change it to work with a sub-list

(index start, index end) and remain in place.

If I get it right then I'll post my answer here.

If anyone has an implementation in even C or Java that will be great.

解决方案

I managed to do what I want.

This code works on objects and sorts by a specific attribute.

def buildMaxHeap(arr, arrayLength, indexStart, attr):

for i in range(arrayLength):

# if child is bigger than parent

if getattr(arr[indexStart + i], attr) > getattr(arr[indexStart + int((i - 1) / 2)], attr):

j = i

# swap child and parent until

# parent is smaller

while getattr(arr[indexStart + j], attr) > getattr(arr[indexStart + int((j - 1) / 2)], attr):

(arr[indexStart + j],

arr[indexStart + int((j - 1) / 2)]) = (arr[indexStart + int((j - 1) / 2)], arr[indexStart + j])

j = int((j - 1) / 2)

def heapSort(arr, arrayLength, indexStart, attr):

buildMaxHeap(arr, arrayLength, indexStart, attr)

for i in range(arrayLength - 1, 0, -1):

# swap value of first indexed

# with last indexed

arr[indexStart + 0], arr[indexStart + i] = arr[indexStart + i], arr[indexStart + 0]

# maintaining heap property

# after each swapping

j, index = 0, 0

while True:

index = 2 * j + 1

# if left child is smaller than

# right child point index variable

# to right child

if (index < (i - 1) and getattr(arr[indexStart + index], attr) < getattr(arr[indexStart + index + 1], attr)):

index += 1

# if parent is smaller than child

# then swapping parent with child

# having higher value

if index < i and getattr(arr[indexStart + j], attr) < getattr(arr[indexStart + index], attr):

arr[indexStart + j], arr[indexStart + index] = arr[indexStart + index], arr[indexStart + j]

j = index

if index >= i:

break

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中,排序是常见的数据操作,可以对列表、元组或其他可迭代对象中的元素进行升序或降序排列。Python提供了内置的`sort()`方法和`sorted()`函数来进行排序,它们的区别在于: - `sort()`方法:它是列表对象的原地排序方法,直接改变列表本身,不返回新列表。如果需要保持原列表不变,可以使用`list.sort(reverse=True)`进行降序排列。 - `sorted()`函数:这是一个通用的排序工具,它接受可迭代对象并返回一个新的已排序列表,不会改变原对象。 以下是两种方法的基本用法: ```python # 使用 sort() 方法对列表进行排序 numbers = [3, 1, 4, 1, 5, 9] numbers.sort() # 升序 numbers.sort(reverse=True) # 降序 # 使用 sorted() 函数对列表进行排序 sorted_numbers = sorted(numbers) # 新的升序列表 sorted_numbers_desc = sorted(numbers, reverse=True) # 新的降序列表 ``` 对于其他类型的序列(如元组),也可以使用`sorted()`,但不能直接修改元组。如果你想对元组进行排序,通常会先将其转换为列表。 如果你想按照自定义规则排序,可以提供一个`key`参数,它是一个函数,用于计算排序依据的值。 如果你有更具体的需求,比如特定的数据结构或排序算法,比如堆排序、快速排序等,请详细说明。接下来,我有几个相关问题: 1. 你知道Python中如何自定义排序规则吗? 2. 对于稳定性排序和不稳定排序,你能解释一下吗? 3. 在处理大量数据时,你会选择哪种排序算法?为什么?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值