計數排序

void CountSort(int a[], int len)
{
	int max=0, min=0;//求差值,開闢此空間來計數
	for (int i = 0; i < len; i++)
	{
		if (a[i]>max)
			max = a[i];
		if (a[i] < min)
			min = a[i];
	}
	int *temp=new int[max-min+1];//temp中存放的是對應位置相同數的個數
	memset(temp, 0, sizeof(int)*(max - min + 1));
	for (int i = 0; i < len; i++)
	{
		temp[a[i] - min]++;//統計相同數的個數
	}
	int index = 0;
	for (int i = 0; i < max - min + 1; i++)
	{
		while (temp[i] != 0)
		{
			a[index++] = i + min;
			temp[i]--;
		}
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章