Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update 堆排序.md -- 优化 #50

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 32 additions & 31 deletions animation-simulation/数据结构和算法/堆排序.md
Original file line number Diff line number Diff line change
Expand Up @@ -219,51 +219,51 @@ def sink(nums: list, index: int, len: int):
Java Code:

```java
class Solution {
public class Solution {

int rollBack(int i) {
return i - 1;
}

public int[] sortArray(int[] nums) {

int len = nums.length;
int[] a = new int[len + 1];

for (int i = 0; i < nums.length; ++i) {
a[i+1] = nums[i];
}
//下沉建堆
for (int i = len/2; i >= 1; --i) {
sink(a,i,len);
for (int i = len / 2; i >= 1; --i) {
sink(nums, i, len);
}

int k = len;
//排序
while (k > 1) {
swap(a,1,k--);
sink(a,1,k);
}
for (int i = 1; i < len+1; ++i) {
nums[i-1] = a[i];
swap(nums, 1, k--);
sink(nums, 1, k);
}

return nums;
}
public void sink (int[] nums, int k,int end) {

public void sink(int[] nums, int k, int end) {
//下沉
while (2 * k <= end) {
int j = 2 * k;
//找出子节点中最大或最小的那个
if (j + 1 <= end && nums[j + 1] > nums[j]) {
if (j + 1 <= end && nums[rollBack(j + 1)] > nums[rollBack(j)]) {
j++;
}
if (nums[j] > nums[k]) {
if (nums[rollBack(j)] > nums[rollBack(k)]) {
swap(nums, j, k);
} else {
break;
}
k = j;
}
}
public void swap (int nums[], int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;

void swap(int[] nums, int i, int j) {
int temp = nums[rollBack(i)];
nums[rollBack(i)] = nums[rollBack(j)];
nums[rollBack(j)] = temp;
}

}
Expand All @@ -272,39 +272,40 @@ class Solution {
Python Code:

```python
def rollBack(i: int):
return i - 1

def sortArray(nums: list)->list:
leng = len(nums)
a = [0] + nums
# 下沉建堆
for i in range(int(leng / 2), 0, -1):
sink(a, i, leng)
sink(nums, i, leng)

k = leng
# 排序
while k > 1:
swap(a, 1, k)
swap(nums, 1, k)
k -= 1
sink(a, 1, k)
sink(nums, 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
temp = nums[rollBack(i)]
nums[rollBack(i)] = nums[rollBack(j)]
nums[rollBack(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]:
if j + 1 <= end and nums[rollBack(j + 1)] > nums[rollBack(j)]:
j += 1
if nums[j] > nums[k]:
if nums[rollBack(j)] > nums[rollBack(k)]:
swap(nums, j, k)
else:
break
k = j

```

好啦,堆排序我们就到这里啦,是不是搞定啦,总的来说堆排序比其他排序算法稍微难理解一些,重点就是建堆,而且应用比较广泛,大家记得打卡呀。
Expand Down