前言
一種將無序數(shù)組進(jìn)行排序的方法弛车。
計數(shù)排序该园,wiki參考:
https://zh.wikipedia.org/wiki/%E8%AE%A1%E6%95%B0%E6%8E%92%E5%BA%8F
計數(shù)排序,主要思想:
- 引入臨時數(shù)組忽舟。
- 對于元素i双妨,計算出比i小的數(shù)淮阐,從而確定i的位置。
- 計算i的重復(fù)刁品,填充數(shù)組泣特。
環(huán)境
編輯器:vs2019
文件:.c類型
正文
代碼參考:
#include <stdio.h>
// 計數(shù)排序,
// 1. 引入臨時數(shù)組挑随。
// 2. 對于元素i状您,計算出比i小的數(shù),從而確定i的位置兜挨。
// 3. 計算i的重復(fù)膏孟,填充數(shù)組。
void count_sort_normal(int source_array[], int source_array_length)
{
int i, j, k;
// 定義臨時數(shù)組拌汇,并且初始值為0
int* tmp_group = (int*)calloc(sizeof(int) * source_array_length);
// 目標(biāo)元素在有序數(shù)組中的索引
int target_index;
// 目標(biāo)元素的重復(fù)數(shù)
int target_num;
for (i = 0; i < source_array_length; i++)
{
target_index = 0;
target_num = 0;
for (j = 0; j < source_array_length; j++)
{
// 遍歷得出目標(biāo)元素的索引
if (source_array[j] < source_array[i])
{
target_index++;
}
else
{
// 計算重復(fù)數(shù)
if (source_array[j] == source_array[i])
{
target_num++;
}
}
}
// 對臨時數(shù)組填充柒桑。當(dāng)臨時數(shù)組中的值為0時,說明未填充噪舀。當(dāng)前元素為0時魁淳,無需填充。
if (tmp_group[target_index] == 0 && source_array[i] !=0 )
{
// 根據(jù)重復(fù)數(shù)填充
for (k = 1; k <= target_num; k++)
{
tmp_group[target_index] = source_array[i];
target_index++;
}
}
}
// 將原數(shù)組替換
for (i = 0; i < source_array_length; i++)
{
source_array[i] = tmp_group[i];
}
}
int main()
{
// 生成隨機測試列表
int test_list[20];
int test_list_length = sizeof(test_list) / sizeof(int);
printf("測試列表: \n");
for (int i = 0; i < test_list_length; i++)
{
test_list[i] = rand() % 100;
printf("%d ", test_list[i]);
}
printf("\n");
// 普通計數(shù)排序
count_sort_normal(test_list, test_list_length);
printf("普通計數(shù)排序結(jié)果: \n");
for (int i = 0; i < test_list_length; i++)
{
printf("%d ", test_list[i]);
}
printf("\n");
return 0;
}
執(zhí)行結(jié)果參考:
image.png