forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSort an Array.java
47 lines (42 loc) · 1.42 KB
/
Sort an Array.java
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
// Runtime: 35 ms (Top 28.44%) | Memory: 75.6 MB (Top 11.81%)
class Solution {
public void downHeapify(int[] nums, int startIndex, int lastIndex){
int parentIndex = startIndex;
int leftChildIndex = 2*parentIndex + 1;
int rightChildIndex = 2*parentIndex + 2;
while(leftChildIndex <= lastIndex){
int maxIndex = parentIndex;
if(nums[leftChildIndex] > nums[maxIndex]){
maxIndex = leftChildIndex;
}
if(rightChildIndex <= lastIndex && nums[rightChildIndex] > nums[maxIndex]){
maxIndex = rightChildIndex;
}
if(maxIndex == parentIndex){
return;
}
int temp = nums[maxIndex];
nums[maxIndex] = nums[parentIndex];
nums[parentIndex] = temp;
parentIndex = maxIndex;
leftChildIndex = 2*parentIndex + 1;
rightChildIndex = 2*parentIndex + 2;
}
return;
}
public int[] sortArray(int[] nums) {
int len = nums.length;
//building a heap - O(n) time
for(int i=(len/2)-1;i>=0;i--){
downHeapify(nums,i,len-1);
}
//sorting element - nlogn(n) time
for(int i=len -1 ;i>0;i--){
int temp = nums[i];
nums[i] = nums[0];
nums[0] = temp;
downHeapify(nums,0,i-1);
}
return nums;
}
}