github.com/matrixorigin/matrixone@v0.7.0/pkg/vm/engine/tae/mergesort/bools/func.go (about)

     1  // Copyright 2021 Matrix Origin
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package bools
    16  
    17  import (
    18  	"github.com/matrixorigin/matrixone/pkg/vm/engine/tae/containers"
    19  )
    20  
    21  func Sort(col containers.Vector, idx []uint32) {
    22  	n := len(idx)
    23  	dataWithIdx := make(sortSlice, n)
    24  
    25  	for i := 0; i < n; i++ {
    26  		dataWithIdx[i] = sortElem{data: col.Get(i).(bool), idx: uint32(i)}
    27  	}
    28  
    29  	sortUnstable(dataWithIdx)
    30  
    31  	for i, v := range dataWithIdx {
    32  		idx[i] = v.idx
    33  		col.Update(i, v.data)
    34  	}
    35  }
    36  
    37  func Merge(col []containers.Vector, src *[]uint32, fromLayout, toLayout []uint32) (ret []containers.Vector, mapping []uint32) {
    38  	ret = make([]containers.Vector, len(toLayout))
    39  	mapping = make([]uint32, len(*src))
    40  
    41  	offset := make([]uint32, len(fromLayout))
    42  	offset[0] = 0
    43  	for i := 1; i < len(fromLayout); i++ {
    44  		offset[i] = offset[i-1] + fromLayout[i-1]
    45  	}
    46  
    47  	for i := range toLayout {
    48  		ret[i] = containers.MakeVector(col[0].GetType(), col[0].Nullable())
    49  	}
    50  
    51  	nBlk := len(col)
    52  	heap := make(heapSlice, nBlk)
    53  
    54  	for i := 0; i < nBlk; i++ {
    55  		heap[i] = heapElem{data: col[i].Get(0).(bool), src: uint32(i), next: 1}
    56  	}
    57  	heapInit(heap)
    58  
    59  	k := 0
    60  	for i := 0; i < len(toLayout); i++ {
    61  		for j := 0; j < int(toLayout[i]); j++ {
    62  			top := heapPop(&heap)
    63  			(*src)[k] = top.src
    64  			ret[i].Append(top.data)
    65  			mapping[offset[top.src]+top.next-1] = uint32(k)
    66  			k++
    67  			if int(top.next) < int(fromLayout[top.src]) {
    68  				heapPush(&heap, heapElem{data: col[top.src].Get(int(top.next)).(bool), src: top.src, next: top.next + 1})
    69  			}
    70  		}
    71  	}
    72  	for _, v := range col {
    73  		v.Close()
    74  	}
    75  	return
    76  }