Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

新增冒泡排序的c++实现 #551

Merged
merged 7 commits into from
Sep 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 72 additions & 1 deletion basic/sorting/BubbleSort/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,78 @@ func main() {
}
```

<!-- tabs:end -->
### **C++**
```c++
#include <iostream>
#include <vector>
#include <string>

using namespace std;

/* 简单版本 */
void bubblesort( vector<int> & vec )
{
for ( int i = 0; i < vec.size() - 1; i++ )
{
for ( int j = 0; j < vec.size() - i - 1; j++ )
{
if ( vec[j] > vec[j + 1] )
{
swap( vec[j], vec[j + 1] );
}
}
}
}


/* 改进版本 */
void bubblesort1( vector<int> & vec )
{
for ( int i = 0; i < vec.size() - 1; i++ )
{
bool exchange = false;
for ( int j = 0; j < vec.size() - i - 1; j++ )
{
if ( vec[j] > vec[j + 1] )
{
swap( vec[j], vec[j + 1] );
exchange = true;
}
}

if ( !exchange )
{
break;
}
}
}


void printvec( const vector<int> & vec, const string & strbegin = "", const string & strend = "" )
{
cout << strbegin << endl;
for ( auto val : vec )
{
cout << val << "\t";
}

cout << endl;
cout << strend << endl;
}


int main( void )
{
vector<int> vec = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
printvec( vec );

bubblesort1( vec );

printvec( vec, "after sort", "" );
}


```

## 算法分析

Expand Down
69 changes: 69 additions & 0 deletions basic/sorting/BubbleSort/bubblesort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#include <iostream>
#include <vector>
#include <string>

using namespace std;

/* 简单版本 */
void bubblesort( vector<int> & vec )
{
for ( int i = 0; i < vec.size() - 1; i++ )
{
for ( int j = 0; j < vec.size() - i - 1; j++ )
{
if ( vec[j] > vec[j + 1] )
{
swap( vec[j], vec[j + 1] );
}
}
}
}


/* 改进版本 */
void bubblesort1( vector<int> & vec )
{
for ( int i = 0; i < vec.size() - 1; i++ )
{
bool exchange = false;
for ( int j = 0; j < vec.size() - i - 1; j++ )
{
if ( vec[j] > vec[j + 1] )
{
swap( vec[j], vec[j + 1] );
exchange = true;
}
}

if ( !exchange )
{
break;
}
}
}


void printvec( const vector<int> & vec, const string & strbegin = "", const string & strend = "" )
{
cout << strbegin << endl;
for ( auto val : vec )
{
cout << val << "\t";
}

cout << endl;
cout << strend << endl;
}


int main( void )
{
vector<int> vec = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };
printvec( vec );

bubblesort1( vec );

printvec( vec, "after sort", "" );
}