📜  计数排序算法

📅  最后修改于: 2020-09-27 17:03:06             🧑  作者: Mango

在本教程中,您将学习计数排序的工作原理。此外,您还将找到C,C++,Java和Python中计数排序的工作示例。

计数排序是一种排序算法,它通过计算数组中每个唯一元素的出现次数来对数组的元素进行排序。将计数存储在辅助数组中,并通过将计数映射为辅助数组的索引来完成排序。


计数排序如何工作?

  1. 从给定数组中找出最大元素(让它成为max )。
    Counting Sort steps
    给定数组
  2. 使用所有元素0初始化一个长度为max+1的数组。此数组用于存储数组中元素的数量。
    Counting Sort Step
    计数数组
  3. 将每个元素的计数存储在count数组中的相应索引处

    例如:如果元素3的计数为2,则将2存储在计数数组的第3个位置。如果数组中不存在元素“ 5″,则在第5个位置存储0。

    Counting Sort Step
    存储的每个元素的计数
  4. 存储计数数组元素的累积和。它有助于将元素放入已排序数组的正确索引中。
    Counting Sort Step
    累计数
  5. 在count数组中找到原始数组的每个元素的索引。这给出了累计计数。将元素放置在计算出的索引处,如下图所示。
    Counting Sort Steps
    计数排序
  6. 将每个元素放置在正确位置后,将其数量减少一。

计数排序算法

countingSort(array, size)
  max 

Python,Java和C / C++示例

Python
爪哇
C
C++
# Counting sort in Python programming


def countingSort(array):
    size = len(array)
    output = [0] * size

    # Initialize count array
    count = [0] * 10

    # Store the count of each elements in count array
    for i in range(0, size):
        count[array[i]] += 1

    # Store the cummulative count
    for i in range(1, 10):
        count[i] += count[i - 1]

    # Find the index of each element of the original array in count array
    # place the elements in output array
    i = size - 1
    while i >= 0:
        output[count[array[i]] - 1] = array[i]
        count[array[i]] -= 1
        i -= 1

    # Copy the sorted elements into original array
    for i in range(0, size):
        array[i] = output[i]


data = [4, 2, 2, 8, 3, 3, 1]
countingSort(data)
print("Sorted Array in Ascending Order: ")
print(data)
// Counting sort in Java programming

import java.util.Arrays;

class CountingSort {
  void countSort(int array[], int size) {
    int[] output = new int[size + 1];

    // Find the largest element of the array
    int max = array[0];
    for (int i = 1; i < size; i++) {
      if (array[i] > max)
        max = array[i];
    }
    int[] count = new int[max + 1];

    // Initialize count array with all zeros.
    for (int i = 0; i < max; ++i) {
      count[i] = 0;
    }

    // Store the count of each element
    for (int i = 0; i < size; i++) {
      count[array[i]]++;
    }

    // Store the cummulative count of each array
    for (int i = 1; i <= max; i++) {
      count[i] += count[i - 1];
    }

    // Find the index of each element of the original array in count array, and
    // place the elements in output array
    for (int i = size - 1; i >= 0; i--) {
      output[count[array[i]] - 1] = array[i];
      count[array[i]]--;
    }

    // Copy the sorted elements into original array
    for (int i = 0; i < size; i++) {
      array[i] = output[i];
    }
  }

  // Driver code
  public static void main(String args[]) {
    int[] data = { 4, 2, 2, 8, 3, 3, 1 };
    int size = data.length;
    CountingSort cs = new CountingSort();
    cs.countSort(data, size);
    System.out.println("Sorted Array in Ascending Order: ");
    System.out.println(Arrays.toString(data));
  }
}
// Counting sort in C programming

#include 

void countingSort(int array[], int size) {
  int output[10];

  // Find the largest element of the array
  int max = array[0];
  for (int i = 1; i < size; i++) {
    if (array[i] > max)
      max = array[i];
  }

  // The size of count must be at least (max+1) but
  // we cannot declare it as int count(max+1) in C as
  // it does not support dynamic memory allocation.
  // So, its size is provided statically.
  int count[10];

  // Initialize count array with all zeros.
  for (int i = 0; i <= max; ++i) {
    count[i] = 0;
  }

  // Store the count of each element
  for (int i = 0; i < size; i++) {
    count[array[i]]++;
  }

  // Store the cummulative count of each array
  for (int i = 1; i <= max; i++) {
    count[i] += count[i - 1];
  }

  // Find the index of each element of the original array in count array, and
  // place the elements in output array
  for (int i = size - 1; i >= 0; i--) {
    output[count[array[i]] - 1] = array[i];
    count[array[i]]--;
  }

  // Copy the sorted elements into original array
  for (int i = 0; i < size; i++) {
    array[i] = output[i];
  }
}

// Function to print an array
void printArray(int array[], int size) {
  for (int i = 0; i < size; ++i) {
    printf("%d  ", array[i]);
  }
  printf("\n");
}

// Driver code
int main() {
  int array[] = {4, 2, 2, 8, 3, 3, 1};
  int n = sizeof(array) / sizeof(array[0]);
  countingSort(array, n);
  printArray(array, n);
}
// Counting sort in C++ programming

#include 
using namespace std;

void countSort(int array[], int size) {
  // The size of count must be at least the (max+1) but
  // we cannot assign declare it as int count(max+1) in C++ as
  // it does not support dynamic memory allocation.
  // So, its size is provided statically.
  int output[10];
  int count[10];
  int max = array[0];

  // Find the largest element of the array
  for (int i = 1; i < size; i++) {
    if (array[i] > max)
      max = array[i];
  }

  // Initialize count array with all zeros.
  for (int i = 0; i <= max; ++i) {
    count[i] = 0;
  }

  // Store the count of each element
  for (int i = 0; i < size; i++) {
    count[array[i]]++;
  }

  // Store the cummulative count of each array
  for (int i = 1; i <= max; i++) {
    count[i] += count[i - 1];
  }

  // Find the index of each element of the original array in count array, and
  // place the elements in output array
  for (int i = size - 1; i >= 0; i--) {
    output[count[array[i]] - 1] = array[i];
    count[array[i]]--;
  }

  // Copy the sorted elements into original array
  for (int i = 0; i < size; i++) {
    array[i] = output[i];
  }
}

// Function to print an array
void printArray(int array[], int size) {
  for (int i = 0; i < size; i++)
    cout << array[i] << " ";
  cout << endl;
}

// Driver code
int main() {
  int array[] = {4, 2, 2, 8, 3, 3, 1};
  int n = sizeof(array) / sizeof(array[0]);
  countSort(array, n);
  printArray(array, n);
}

复杂

时间复杂度:

主要有四个主要循环。 (可以在函数外部找到最大值。)

for-loop time of counting
1st O(max)
2nd O(size)
3rd O(max)
4th O(size)

总体复杂度= O(max)+O(size)+O(max)+O(size) = O(max+size)

  • 最坏情况下的复杂度: O(n+k)
  • 最佳案例复杂度: O(n+k)
  • 平均案例复杂度: O(n+k)

在上述所有情况下,复杂度是相同的,因为无论元素如何放置在数组中,该算法都会经历n+k次。

没有任何元素之间的比较,因此它比基于比较的排序技术要好。但是,如果整数很大,那是不好的,因为应该制作该大小的数组。

空间复杂度:

计数排序的空间复杂度为O(max) 。元素范围越大,空间复杂度越大。


计算排序应用程序

在以下情况下使用计数排序:

  • 有多个较小的整数。
  • 线性复杂度是必要的。