C++ 计数排序
計數排序的原理:
(1)首先,找出最大的元素,給“count[ ]”申請“最大元素的下標+1”個單元(因為數組下標是從0開始的,所以要+1);
(2)然后,統計每個元素出現的次數,把次數存到“count[ ]”里;
(3)最后,通過一個元素出現的次數-1,從而算出正確順序的位置,再把元素放進去,就有順序了。
? 因為不知道范圍的大小,所以需要申請內存,如果知道范圍的大小,就可以直接聲明。
?
#include <iostream>
#include <stdlib.h>
using namespace std;
?
/**********************************************/
/* ?計數排序
/*********************************************/
?
void CountingSort(int array[], int n)
{
?? ?int i;
?? ?int largest = array[0]; ?//設最初最大元素默認是array[0]
?? ?int *temp = new int[n]; ?//申請一個n個int元素的數組內存
?
?? ?for (i = 1; i < n; i++)
?? ?{
?? ??? ?if (largest < array[i]) ?//找出最大元素
?? ??? ?{
?? ??? ??? ?largest = array[i];
?? ??? ?}
?? ?}
?
?? ?int *count = new int[largest + 1]; ?//申請一個[largest+1]個int元素的數組內存
?? ?for (i = 0; i <= largest; i++)
?? ?{
?? ??? ?count[i] = 0; ?//初始化
?? ?}
?
?? ?for (i = 0; i < n; i++)
?? ?{
?? ??? ?count[array[i]]++; ?//計算array數組每個元素出現的次數
?? ?}
?
?? ?for (i = 1; i <= largest; i++)
?? ?{
?? ??? ?count[i] = count[i - 1] + count[i]; ?//count數組元素出現次數的累加
?? ?}
?
?? ?for (i = n - 1; i >= 0; i--)
?? ?{
?? ??? ?temp[count[array[i]] - 1] = array[i]; ?//將array[]數組的元素賦給已經排好位置的temp[]數組
?? ??? ?count[array[i]]--; ?//數組元素的總次數減少
?? ?}
?
?? ?for (i = 0; i < n; i++)
?? ?{
?? ??? ?array[i] = temp[i]; ?//將排好順序的元素賦給array[]數組
?? ?}
?
?? ?delete[] count; ?//釋放內存
?? ?count = NULL;
?? ?delete[] temp; ?//釋放內存
?? ?temp = NULL;
}
?
?
int main(void) ?//主程序
{
?? ?const int n = 6; ?//數組元素的數量
?? ?int array[n];
?? ?cout << "請輸入6個整數:" << endl;
?? ?for (int i = 0; i < n; i++)
?? ?{
?? ??? ?cin >> array[i];
?? ?}
?
?? ?cout << endl; ?//換行
?
?? ?CountingSort(array, n); ?// 調用CountingSort函數 ?進行排序
?
?? ?cout << "由小到大的順序排列后:" << endl;
?? ?for (int i = 0; i < n; i++)
?? ?{
?? ??? ?cout << "Array" << "[" << i << "]" << " = " << array[i] << endl;
?? ?}
?
?? ?cout << endl << endl; ?//換行
?
?? ?system("pause"); ?//調試時,黑窗口不會閃退,一直保持
?? ?return 0;
}
?
總結
- 上一篇: 求int在二进制存储时1的个数(C++)
- 下一篇: 简谈C/C++学习路线