/* ----------------------------------------------------------------------------- Copyright 2021 Kevin P. Barry Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ----------------------------------------------------------------------------- */ // Author: Kevin P. Barry [ta0kira@gmail.com] define Sorting { sort (seq) { \ sortWith<#x,#x>(seq) } sortWith (seq) { \ HeapSort<#x,#xx>.inPlace(seq) } reverse (seq) { traverse (Counter.zeroIndexed(seq.size()/2) -> Int i) { Int j <- seq.size()-i-1 #x temp <- seq.readAt(i) \ seq.writeAt(i,seq.readAt(j)) \ seq.writeAt(j,temp) } } } // Putting the params at the top level allows helpers to be called without // needing to pass the params every time. concrete HeapSort<#x,#xx> { #xx defines LessThan<#x> @type inPlace ([ReadAt<#x>&WriteAt<#x>]) -> () } define HeapSort { $ReadOnly[seq]$ @value [ReadAt<#x>&WriteAt<#x>] seq inPlace (seq) { \ (#self{ seq }).execute() } @value execute () -> () execute () { // Convert the container to a heap. traverse (Counter.revZeroIndexed(seq.size()/2) -> Int i) { \ sift(i,seq.size()) } // Traverse the heap and populate the container in place. traverse (Counter.revZeroIndexed(seq.size()) -> Int i) { $ReadOnly[i]$ \ swap(0,i) \ sift(0,i) } } @value sift (Int,Int) -> () sift (start,size) { scoped { Int last <- start Int indexLargest <- last $Hidden[start]$ } in while (2*last+1 < size) { $ReadOnly[last]$ Int left <- 2*last+1 Int right <- 2*last+2 $ReadOnly[left,right]$ if (seq.readAt(indexLargest) `#xx.lessThan` seq.readAt(left)) { indexLargest <- left } if (right < size && seq.readAt(indexLargest) `#xx.lessThan` seq.readAt(right)) { indexLargest <- right } if (indexLargest == last) { break } } update { \ swap(last,indexLargest) last <- indexLargest } } @value swap (Int,Int) -> () swap (i,j) { if (i != j) { #x temp <- seq.readAt(i) \ seq.writeAt(i,seq.readAt(j)) \ seq.writeAt(j,temp) } } }