Swap的簡單實現
- //C語言方式(by-pointer):
- template <typename Type>
- bool swapByPointer(Type *pointer1, Type *pointer2)
- {
- //確保兩個指針不會指向同一個對象
- if (pointer1 == NULL || pointer2 == NULL)
- {
- return false;
- }
- if (pointer1 != pointer2)
- {
- Type tmp = *pointer1;
- *pointer1 = *pointer2;
- *pointer2 = tmp;
- }
- return true;
- }
- //C++特有方式(by-reference):
- template <typename Type>
- void swapByReference(Type &value1, Type &value2)
- {
- if (value2 != value1)
- {
- Type tmp = value1;
- value1 = value2;
- value2 = tmp;
- }
- }
小結:
雖然我們自己實現了swap,但我們還是比較推薦使用C++ STL已經實現好的std::swap()函數,其存在於命名空間std中,使用實例如下面的<冒泡排序>.
冒泡排序(Bubble-Sort)
算法思想:
從左到右掃描數據,找出最大的元素,將其放到數組右邊;
過程:
循環比較相鄰的兩個數,如果左邊的數比右邊的大,則交換兩個數;
- //實現:注意代碼中的三個注意點(x):
- template <typename Type>
- void bubbleSort(Type *begin, Type *end)
- {
- if ((begin == end) || (begin == NULL) || (end == NULL))
- return ;
- int length = end - begin;
- //注意點(1):保證一旦數組有序, 則會直接停止排序, 不會在繼續進行無用的循環
- bool isOrder = false;
- //外層循環控制掃描次數(length-1)
- //注意點(2):N個元素其實只需N-1次掃描
- for (int i = 0; !isOrder && i < length-1; ++i)
- {
- //首先假定這次數組已經有序
- isOrder = true;
- //注意點(3):確保能夠從0掃描到最後一個未排序的元素
- for (Type *iter = begin; iter < end-i-1; ++iter)
- {
- //如果前面的左邊的元素>右邊的元素
- if (*iter > *(iter+1))
- {
- //交換
- std::swap(*iter, *(iter+1));
- isOrder = false;
- }
- }
- }
- }
- template <typename Type>
- void bubbleSort(Type *array, int length)
- {
- return bubbleSort(array, array+length);
- }
選擇排序(Select-Sort)
思想:
從當前尚未排序的序列中選擇一個最小的元素, 將之放到已排序的序列的隊列的末尾;
要點:
1.注意三個指針(inner, outer, miner)所代表的含義;
2.同時注意是從未排序的序列中進行查找最小元素!
- //實現
- template <typename Type>
- void selectSort(Type *begin, Type *end)
- {
- if ((begin == end) || (begin == NULL) || (end == NULL))
- return ;
- //只要循環到最後一個元素的前一個就行了,因爲剩下的那個肯定是最大的
- for (Type *outer = begin; outer < end-1; ++outer)
- {
- //注意:是從尚未排序的序列中查找(miner = outer, inner = outer+1)
- Type *miner = outer;
- //從miner+1開始遍歷數組, 尋找一個元素值小於*miner的
- for (Type *inner = outer+1; inner < end; ++inner)
- {
- if (*inner < *miner)
- miner = inner;
- }
- if (miner != outer)
- std::swap(*miner, *outer);
- }
- }
- //爲了能夠讓STL的標準容器如vector使用
- template <typename Iterator>
- void selectSort(Iterator iter1, Iterator iter2)
- {
- return selectSort(&(*iter1), &(*iter2));
- }
- template <typename Type>
- void selectSort(Type *array, int length)
- {
- return selectSort(array, array+length);
- }
小結:
雖然我們自己實現了Bubble-Sort和Select-Sort,但我們在實際軟件開發中一般是不會用到的,因爲的它的效率爲O(N^2),效率太慢^_^, 因此我們還是推薦使用C++ STL中已經實現了的std::sort(), 其內部原理使用了快速排序, 效率爲O(logN)速度非常快.
附-測試程序
- int main()
- {
- srand(time(NULL));
- vector<double> dVec;
- int count = 10;
- while (count --)
- {
- dVec.push_back((rand()%1000)/100.0);
- }
- selectSort(dVec.begin(), dVec.end());
- for (vector<double>::iterator iter = dVec.begin(); iter < dVec.end(); ++iter)
- {
- cout << *iter << endl;
- }
- return 0;
- }