Skip to content
This repository was archived by the owner on May 18, 2019. It is now read-only.

Commit aa30cda

Browse files
hkielOpenModelica-Hudson
authored andcommitted
implemented heap sort for arrays
Belonging to [master]: - #2048
1 parent 6dc1882 commit aa30cda

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Compiler/Util/Array.mo

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,50 @@ algorithm
8282
end for;
8383
end mapNoCopy_1;
8484

85+
protected function downheap
86+
input output array<Integer> inArray;
87+
input Integer vIn;
88+
protected
89+
Integer v = vIn;
90+
Integer w = 2*v+1;
91+
Integer n = arrayLength(inArray);
92+
Integer tmp;
93+
algorithm
94+
while w<n loop
95+
if w+1 < n then
96+
if inArray[w+2]>inArray[w+1] then
97+
w := w + 1;
98+
end if;
99+
end if;
100+
if inArray[v+1]>=inArray[w+1] then
101+
return;
102+
end if;
103+
tmp := inArray[v+1];
104+
inArray[v+1] := inArray[w+1];
105+
inArray[w+1] := tmp;
106+
v := w;
107+
w := 2*v + 1;
108+
end while;
109+
end downheap;
110+
111+
public function heapSort
112+
input output array<Integer> inArray;
113+
protected
114+
Integer n = arrayLength(inArray);
115+
Integer tmp;
116+
algorithm
117+
for v in (intDiv(arrayLength(inArray),2)-1):-1:0 loop
118+
downheap(inArray, v);
119+
end for;
120+
while n>1 loop
121+
n := n - 1;
122+
tmp := inArray[1];
123+
inArray[1] := inArray[n+1];
124+
inArray[n+1] := tmp;
125+
downheap(inArray, 0);
126+
end while;
127+
end heapSort;
128+
85129
function findFirstOnTrue<T>
86130
input array<T> inArray;
87131
input FuncType inPredicate;

0 commit comments

Comments
 (0)