github.com/gogf/gf/v2@v2.7.4/container/garray/garray_func.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package garray
     8  
     9  import "strings"
    10  
    11  // defaultComparatorInt for int comparison.
    12  func defaultComparatorInt(a, b int) int {
    13  	if a < b {
    14  		return -1
    15  	}
    16  	if a > b {
    17  		return 1
    18  	}
    19  	return 0
    20  }
    21  
    22  // defaultComparatorStr for string comparison.
    23  func defaultComparatorStr(a, b string) int {
    24  	return strings.Compare(a, b)
    25  }
    26  
    27  // quickSortInt is the quick-sorting algorithm implements for int.
    28  func quickSortInt(values []int, comparator func(a, b int) int) {
    29  	if len(values) <= 1 {
    30  		return
    31  	}
    32  	mid, i := values[0], 1
    33  	head, tail := 0, len(values)-1
    34  	for head < tail {
    35  		if comparator(values[i], mid) > 0 {
    36  			values[i], values[tail] = values[tail], values[i]
    37  			tail--
    38  		} else {
    39  			values[i], values[head] = values[head], values[i]
    40  			head++
    41  			i++
    42  		}
    43  	}
    44  	values[head] = mid
    45  	quickSortInt(values[:head], comparator)
    46  	quickSortInt(values[head+1:], comparator)
    47  }
    48  
    49  // quickSortStr is the quick-sorting algorithm implements for string.
    50  func quickSortStr(values []string, comparator func(a, b string) int) {
    51  	if len(values) <= 1 {
    52  		return
    53  	}
    54  	mid, i := values[0], 1
    55  	head, tail := 0, len(values)-1
    56  	for head < tail {
    57  		if comparator(values[i], mid) > 0 {
    58  			values[i], values[tail] = values[tail], values[i]
    59  			tail--
    60  		} else {
    61  			values[i], values[head] = values[head], values[i]
    62  			head++
    63  			i++
    64  		}
    65  	}
    66  	values[head] = mid
    67  	quickSortStr(values[:head], comparator)
    68  	quickSortStr(values[head+1:], comparator)
    69  }