// 该函数模板使用冒泡法对集合元素进行排序,参数说明: // collection 集合对象,集合对象必须提供 [] 操作。 // element 集合元素,该参数的作用仅仅是确定集合元素类型, // 参数的值没有用,建议取集合的第一个元素。集合 // 元素必须提供复制、赋值和比较操作。 // count 集合元素的数目 // ascend 表明排序时使用升序(true)还是降序(false) // 该函数模板支持C++数组以及MFC集合CStringArray、CArray。 template <typename COLLECTION_TYPE, typename ELEMENT_TYPE> void BubbleSort(COLLECTION_TYPE& collection, ELEMENT_TYPE element, int count, bool ascend = true) { for (int i = 0; i < count-1; i++) for (int j = 0; j < count-1-i; j++) if (ascend) { // 升序 if (collection[j] > collection[j+1]) { ELEMENT_TYPE temp = collection[j]; collection[j] = collection[j+1]; collection[j+1] = temp; } } else { // 降序 if (collection[j] < collection[j+1]) { ELEMENT_TYPE temp = collection[j]; collection[j] = collection[j+1]; collection[j+1] = temp; } } }下列代码对整型数组按升序排序:
int arrayInt[] = {45, 23, 76, 91, 37, 201, 187};
BubbleSort(arrayInt, arrayInt[0], 7);下列代码对整数集合按升序排序: CArray <int, int> collectionInt; collectionInt.Add(45); collectionInt.Add(23); collectionInt.Add(76); collectionInt.Add(91); collectionInt.Add(37); collectionInt.Add(201); collectionInt.Add(187); BubbleSort(collectionInt, collectionInt[0], collectionInt.GetSize());下列代码对一个字符串数组按降序排序:
CString arrayString[] = {"eagle", "hawk", "falcon"};
BubbleSort(arrayString, arrayString[0], 3, false);
下列代码对一个字符串集合按降序排序:
CStringArray collectionString;
collectionString.Add("eagle");
collectionString.Add("hawk");
collectionString.Add("falcon");
BubbleSort(collectionString, collectionString[0], collectionString.GetSize(), false);





