添加了python版本代码

为数据结构和算法文件夹下的代码增加了python语言版本
This commit is contained in:
goodyong
2021-07-05 22:25:41 +08:00
parent a503e97f11
commit 4e661354d4
16 changed files with 1088 additions and 83 deletions

View File

@@ -3,7 +3,7 @@
> 如果阅读时发现错误或者动画不可以显示的问题可以添加我微信好友 **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
> 感谢支持该仓库会一直维护希望对各位有一丢丢帮助
>
>刷题网站
> 另外希望手机阅读的同学可以来我的 <u>[**公众号袁厨的算法小屋**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
说堆排序之前我们先简单了解一些什么是堆堆这种数据结构应用场景非常多所以我们需要熟练掌握呀
@@ -99,8 +99,10 @@
我们一起来看一下上浮操作代码
Java Code:
```java
public void swim (int index) {
public void swim (int[] nums, int index) {
while (index > 1 && nums[index/2] > nums[index]) {
swap(index/2,index);//交换
index = index/2;
@@ -108,6 +110,15 @@ public void swim (int index) {
}
```
Python Code:
```python
def swim(nums: int, index: int):
while index > 1 and nums[int(index/2)] > nums[index]:
swap(int(index/2), index)# 交换
index = int(index/2)
```
既然利用上浮操作建堆已经搞懂啦那么我们再来了解一下利用下沉操作建堆吧也很容易理解
给我们一个无序数组不满足堆的要求见下图
@@ -145,6 +156,8 @@ public void swim (int index) {
好啦我们一起看哈下沉操作的代码吧
Java Code:
```java
public void sink (int[] nums, int index,int len) {
while (true) {
@@ -165,6 +178,24 @@ public void sink (int[] nums, int index,int len) {
}
```
Python Code:
```python
def sink(nums: list, index: int, len: int):
while True:
# 获取子节点
j = 2 * index
if j < len-1 and nums[j] < nums[j+1]:
j += 1
# 交换操作父节点下沉与最大的孩子节点交换
if j < len and nums[index] < nums[j]:
swap(nums, index, j)
else:
break
# 继续下沉
index = j
```
好啦两种建堆方式我们都已经了解啦那么我们如何进行排序呢
了解排序之前我们先来看一下如何删除堆顶元素我们需要保证的是删除堆顶元素后其他元素仍能满足堆的要求我们思考一下如何实现呢见下图
@@ -187,6 +218,8 @@ public void sink (int[] nums, int index,int len) {
好啦下面我们一起看代码吧
Java Code:
```java
class Solution {
public int[] sortArray(int[] nums) {
@@ -238,6 +271,44 @@ class Solution {
}
```
Python Code:
```python
def sortArray(nums: list)->list:
leng = len(nums)
a = [0] + nums
# 下沉建堆
for i in range(int(leng / 2), 0, -1):
sink(a, i, leng)
k = leng
# 排序
while k > 1:
swap(a, 1, k)
k -= 1
sink(a, 1, k)
for i in range(1, leng + 1):
nums[i - 1] = a[i]
return nums
def swap(nums: list, i: int, j: int):
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
def sink(nums: list, k: int, end: int):
while 2 * k <= end:
j = 2 * k
if j + 1 <= end and nums[j + 1] > nums[j]:
j += 1
if nums[j] > nums[k]:
swap(nums, j, k)
else:
break
k = j
```
好啦堆排序我们就到这里啦是不是搞定啦总的来说堆排序比其他排序算法稍微难理解一些重点就是建堆而且应用比较广泛大家记得打卡呀
好啦我们再来分析一下堆排序的时间复杂度空间复杂度以及稳定性