自己动手写算法.Sort.Bubble
Bubble Sort Algorithm
This is an sorting algorithm which I learned when I began to study the C languange. I never wrote it down even though it's such a simple algorithm.
-
Implementation
C++:
Cs
- /*
- 1. pick the last one as the seed
- 2. if smaller than the previous one, swap it
- 3. else the previous becomes as the seed
- 4. this loop ends until to the 'top'
- we can make sure that the smallest one is on the top each time
- */
- void SortBubble::sort(int arr[], const int nSize)
- {
- ALog::print(_T("# Bubble Sort: /n#"));
- ALog::print(arr, nSize) << LINE_SPLIT;
- int top = 0;
- while( top < nSize-1 )
- {
- ALog::print(_T("# ")) << top << std::endl;
- for(int cur=nSize-1; cur>top; --cur)
- {
- if( arr[cur] < arr[cur-1] )
- {
- std::swap(arr[cur], arr[cur-1]);
- }
- ALog::print(arr, nSize);
- }
- ++top;
- }
- ALog::print(LINE_SPLIT);
- }
-
Test data
The intermediate results:
- # Bubble Sort:
- # 2 9 3 7 8 6 4 5 0 1
- =========================
- # 0
- 2 9 3 7 8 6 4 5 0 1
- 2 9 3 7 8 6 4 0 5 1
- 2 9 3 7 8 6 0 4 5 1
- 2 9 3 7 8 0 6 4 5 1
- 2 9 3 7 0 8 6 4 5 1
- 2 9 3 0 7 8 6 4 5 1
- 2 9 0 3 7 8 6 4 5 1
- 2 0 9 3 7 8 6 4 5 1
- 0 2 9 3 7 8 6 4 5 1
- # 1
- 0 2 9 3 7 8 6 4 1 5
- 0 2 9 3 7 8 6 1 4 5
- 0 2 9 3 7 8 1 6 4 5
- 0 2 9 3 7 1 8 6 4 5
- 0 2 9 3 1 7 8 6 4 5
- 0 2 9 1 3 7 8 6 4 5
- 0 2 1 9 3 7 8 6 4 5
- 0 1 2 9 3 7 8 6 4 5
- # 2
- 0 1 2 9 3 7 8 6 4 5
- 0 1 2 9 3 7 8 4 6 5
- 0 1 2 9 3 7 4 8 6 5
- 0 1 2 9 3 4 7 8 6 5
- 0 1 2 9 3 4 7 8 6 5
- 0 1 2 3 9 4 7 8 6 5
- 0 1 2 3 9 4 7 8 6 5
- # 3
- 0 1 2 3 9 4 7 8 5 6
- 0 1 2 3 9 4 7 5 8 6
- 0 1 2 3 9 4 5 7 8 6
- 0 1 2 3 9 4 5 7 8 6
- 0 1 2 3 4 9 5 7 8 6
- 0 1 2 3 4 9 5 7 8 6
- # 4
- 0 1 2 3 4 9 5 7 6 8
- 0 1 2 3 4 9 5 6 7 8
- 0 1 2 3 4 9 5 6 7 8
- 0 1 2 3 4 5 9 6 7 8
- 0 1 2 3 4 5 9 6 7 8
- # 5
- 0 1 2 3 4 5 9 6 7 8
- 0 1 2 3 4 5 9 6 7 8
- 0 1 2 3 4 5 6 9 7 8
- 0 1 2 3 4 5 6 9 7 8
- # 6
- 0 1 2 3 4 5 6 9 7 8
- 0 1 2 3 4 5 6 7 9 8
- 0 1 2 3 4 5 6 7 9 8
- # 7
- 0 1 2 3 4 5 6 7 8 9
- 0 1 2 3 4 5 6 7 8 9
- # 8
- 0 1 2 3 4 5 6 7 8 9
- =========================
-
Optimization
We can end the loops if there are no swaping operations.
- void SortBubble::sort2(int arr[], const int nSize)
- {
- ALog::print(_T("# Bubble Sort: /n#"));
- ALog::print(arr, nSize) << LINE_SPLIT;
- int top = 0;
- bool bNoSort = false;
- while( !bNoSort && top < nSize-1 )
- {
- bNoSort = true;
- ALog::print(_T("# ")) << top << std::endl;
- for(int cur=nSize-1; cur>top; --cur)
- {
- if( arr[cur] < arr[cur-1] )
- {
- std::swap(arr[cur], arr[cur-1]);
- bNoSort = false;
- }
- ALog::print(arr, nSize);
- }
- ++top;
- }
- ALog::print(LINE_SPLIT);
- }