-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeapSort.m
More file actions
62 lines (56 loc) · 1.35 KB
/
Copy pathHeapSort.m
File metadata and controls
62 lines (56 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//
// HeapSort.m
// BaseAlgorithm
//
// Created by CC on 2020/4/29.
// Copyright © 2020 kayak. All rights reserved.
//
#import "HeapSort.h"
#import "TestUtil.h"
@implementation HeapSort
-(void)test{
int arr[] = {25,3,11,31,5,6,7,33,16,75,19,88,91,34,69,65,23,21,37,68};
[TestUtil printArray:arr length:20];
[self sort:arr length:20];
[TestUtil printArray:arr length:20];
}
void swap(int *arr,int indexA,int indexB){
printf("%d:%d %d:%d\n",indexA,arr[indexA],indexB,arr[indexB]);
int tmp= arr[indexA];
arr[indexA] = arr[indexB];
arr[indexB] = tmp;
}
-(void)sort:(int *)arr length:(int)length{
[TestUtil printArray:arr length:20];
int lastParentIndex = length/2 - 1;
int len = length;
//建堆
for(int i = lastParentIndex;i>=0;i--){
heapify(arr, i, len--);
}
len = length;
while (len) {
swap(arr, 0, len-1);
heapify(arr, 0, --len);
}
}
/**
建堆
*/
void heapify(int *arr,int i,int length){
int leftSon = 2*i+1;
int rightSon = 2*i+2;
while (leftSon<length) {
int maxSon = leftSon;
if(rightSon<length&&arr[leftSon]<arr[rightSon]){
maxSon = rightSon;
}
if(arr[maxSon]>arr[i]){
swap(arr, maxSon, i);
}
i = maxSon;
leftSon = 2*i+1;
rightSon = 2*i+2;
}
}
@end