Skip to content

Commit

Permalink
计数排序中计数容器重命名为 vecCount
Browse files Browse the repository at this point in the history
  • Loading branch information
huihut committed Nov 6, 2018
1 parent 433d20e commit 626c495
Showing 1 changed file with 5 additions and 5 deletions.
10 changes: 5 additions & 5 deletions Algorithm/CountSort.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,19 @@ void CountSort(vector<int>& vecRaw, vector<int>& vecObj)

// 使用 vecRaw 的最大值 + 1 作为计数容器 countVec 的大小
int vecCountLength = (*max_element(begin(vecRaw), end(vecRaw))) + 1;
vector<int> countVec(vecCountLength, 0);
vector<int> vecCount(vecCountLength, 0);

// 统计每个键值出现的次数
for (int i = 0; i < vecRaw.size(); i++)
countVec[vecRaw[i]]++;
vecCount[vecRaw[i]]++;

// 后面的键值出现的位置为前面所有键值出现的次数之和
for (int i = 1; i < vecCountLength; i++)
countVec[i] += countVec[i - 1];
vecCount[i] += vecCount[i - 1];

// 将键值放到目标位置
for (int i = vecRaw.size(); i > 0; i--) // 此处逆序是为了保持相同键值的稳定性
vecObj[--countVec[vecRaw[i - 1]]] = vecRaw[i - 1];
vecObj[--vecCount[vecRaw[i - 1]]] = vecRaw[i - 1];
}

int main()
Expand All @@ -57,6 +57,6 @@ int main()
for (int i = 0; i < vecObj.size(); ++i)
cout << vecObj[i] << " ";
cout << endl;

return 0;
}

0 comments on commit 626c495

Please sign in to comment.