mirror of
https://hub.njuu.cf/TheAlgorithms/C-Plus-Plus.git
synced 2023-10-11 13:05:55 +08:00
Merge pull request #1 from nghiaxlee/nghiaxlee-combsort-patch-1
Add comment to make easier to understand
This commit is contained in:
commit
7fac260d53
11
combsort.cpp
11
combsort.cpp
@ -1,3 +1,8 @@
|
|||||||
|
//Kind of better version of Bubble sort.
|
||||||
|
//While Bubble sort is comparering adjacent value, Combsort is using gap larger than 1
|
||||||
|
//Best case: O(n)
|
||||||
|
//Worst case: O(n ^ 2)
|
||||||
|
|
||||||
#include <bits/stdc++.h>
|
#include <bits/stdc++.h>
|
||||||
|
|
||||||
using namespace std;
|
using namespace std;
|
||||||
@ -12,14 +17,20 @@ int FindNextGap(int x) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void CombSort(int a[], int l, int r) {
|
void CombSort(int a[], int l, int r) {
|
||||||
|
//Init gap
|
||||||
int gap = n;
|
int gap = n;
|
||||||
|
|
||||||
|
//Initialize swapped as true to make sure that loop runs
|
||||||
bool swapped = true;
|
bool swapped = true;
|
||||||
|
|
||||||
|
//Keep running until gap = 1 or none elements were swapped
|
||||||
while (gap != 1 || swapped) {
|
while (gap != 1 || swapped) {
|
||||||
|
//Find next gap
|
||||||
gap = FindNextGap(gap);
|
gap = FindNextGap(gap);
|
||||||
|
|
||||||
swapped = false;
|
swapped = false;
|
||||||
|
|
||||||
|
// Compare all elements with current gap
|
||||||
for(int i = l; i <= r - gap; ++i) {
|
for(int i = l; i <= r - gap; ++i) {
|
||||||
if (a[i] > a[i + gap]) {
|
if (a[i] > a[i + gap]) {
|
||||||
swap(a[i], a[i + gap]);
|
swap(a[i], a[i + gap]);
|
||||||
|
Loading…
x
Reference in New Issue
Block a user