Skip to content

Commit 8bd066f

Browse files
L Xiaojian64json
authored andcommitted
Add C++ implementation in Brute Force/Bubble Sort
1. Decrease-and-conquer 2. Early termination
1 parent 1f65251 commit 8bd066f

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Brute Force/Bubble Sort/main.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include "algorithm-visualizer.h"
2+
3+
#define N 15
4+
#define MIN 1
5+
#define MAX 20
6+
7+
void BubbleSort(int start, int end, int array[]);
8+
9+
ChartTracer chartTracer("Chart");
10+
11+
int main() {
12+
int array[N];
13+
Randomize::Array1D<int>(N, *(new Randomize::Integer(MIN, MAX))).fill(&array[0]);
14+
chartTracer.set(array);
15+
Layout::setRoot(VerticalLayout({ chartTracer }));
16+
17+
BubbleSort(0, N - 1, array);
18+
19+
return 0;
20+
}
21+
22+
void BubbleSort(int start, int end, int array[])
23+
{
24+
chartTracer.select(end);
25+
26+
int newEnd = start;
27+
for(int i = start; i < end; ++i)
28+
{
29+
chartTracer.select(i);
30+
chartTracer.select(i + 1);
31+
Tracer::delay();
32+
if(array[i] > array[i + 1])
33+
{
34+
std::swap(array[i], array[i + 1]);
35+
chartTracer.patch(i, array[i]);
36+
chartTracer.patch(i + 1, array[i + 1]);
37+
Tracer::delay();
38+
chartTracer.depatch(i);
39+
chartTracer.depatch(i + 1);
40+
newEnd = i;
41+
}
42+
43+
chartTracer.deselect(i);
44+
chartTracer.deselect(i + 1);
45+
}
46+
47+
if(newEnd == start)
48+
{
49+
return;
50+
}
51+
else
52+
{
53+
BubbleSort(start, newEnd, array);
54+
}
55+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy