github.com/jfcg/sorty@v1.2.0/sorty.go (about)

     1  /*	Copyright (c) 2019, Serhat Şevki Dinçer.
     2  	This Source Code Form is subject to the terms of the Mozilla Public
     3  	License, v. 2.0. If a copy of the MPL was not distributed with this
     4  	file, You can obtain one at http://mozilla.org/MPL/2.0/.
     5  */
     6  
     7  // Package sorty is a type-specific, fast, efficient, concurrent/parallel QuickSort
     8  // implementation. It is in-place and does not require extra memory. You can call
     9  // corresponding Sort*() to rapidly sort your slices (in ascending order) or
    10  // collections of objects. For example:
    11  //  sorty.SortS(string_slice) // native slice
    12  //  sorty.Sort(n, lesswap)    // lesswap() function based
    13  package sorty
    14  
    15  // Mxg is the maximum concurrent goroutines (including caller) used for sorting
    16  // per Sort*() call. Mxg can be changed live, even during an ongoing Sort*() call.
    17  // Mxg=1 (or a short input) yields single-goroutine sorting: No goroutines or
    18  // channel will be created by sorty.
    19  var Mxg uint32 = 3
    20  
    21  func init() {
    22  	if !(4097 > Mxg && Mxg > 0 && Mlr > 2*Mli && Mli > Hmli && Hmli > 15) {
    23  		panic("sorty: check your Mxg/Mli/Hmli/Mlr values")
    24  	}
    25  }
    26  
    27  // mid-point
    28  func mid(l, h int) int {
    29  	return int(uint(l+h) >> 1)
    30  }
    31  
    32  // Search returns lowest integer k in [0,n) where fn(k) is true, assuming:
    33  //  fn(k) => fn(k+1)
    34  // If there is no such k, it returns n. It can be used to locate an element
    35  // in a sorted collection.
    36  func Search(n int, fn func(int) bool) int {
    37  	l, h := 0, n
    38  
    39  	for l < h {
    40  		m := mid(l, h)
    41  
    42  		if fn(m) {
    43  			h = m
    44  		} else {
    45  			l = m + 1
    46  		}
    47  	}
    48  	return l
    49  }
    50  
    51  // synchronization variables for [g]long*()
    52  type syncVar struct {
    53  	ngr  uint32   // number of sorting goroutines
    54  	done chan int // end signal
    55  }