github.com/benz9527/toy-box/algo@v0.0.0-20240221120937-66c0c6bd5abd/sort/counting.go (about)

     1  package sort
     2  
     3  /*
     4  CountingSort
     5  It sorts the elements of an array by counting the number of occurrences of each unique element in the array.
     6  The count is stored in an auxiliary array and the sorting si done by mapping the count as an index of the auxiliary array.
     7  
     8  1.Find out the maximum element (let ie be maxElement) from the given array.
     9  2.Initialize an array of length as maxElement value + 1 with all elements 0. This array is used for storing the count of
    10  the elements in the array.
    11  3.Store the count of each element at their respective index in count array
    12  4.Store cumulative sum of the elements of the count array. It helps in placing the elements into the correct index of
    13  the sorted array.
    14  5.Find the index of each element of the original array in the count array. This gives the cumulative count. Place the
    15  element at the index calculated.
    16  6.After placing each element at its correct position, decrease its count by one.
    17  */
    18  func CountingSort(arr []int) {
    19  	n := len(arr)
    20  	maxElem := arr[0]
    21  	for i := 1; i < n; i++ {
    22  		if arr[i] > maxElem {
    23  			maxElem = arr[i]
    24  		}
    25  	}
    26  
    27  	maxLen := maxElem + 1
    28  	auxCountingArr := make([]int, maxLen)
    29  
    30  	for i := 0; i < n; i++ {
    31  		auxCountingArr[arr[i]] = auxCountingArr[arr[i]] + 1
    32  	}
    33  
    34  	originIdx := 0
    35  	for i := 0; i < maxLen; i++ {
    36  		for auxCountingArr[i] > 0 {
    37  			arr[originIdx] = i
    38  			auxCountingArr[i] = auxCountingArr[i] - 1
    39  			originIdx = originIdx + 1
    40  		}
    41  	}
    42  }