---
# System prepended metadata

title: B8 Bubble Sort
tags: [作業題目解答]

---

###### tags: `作業題目解答`

B8 Bubble Sort
===

[TOC]

## 解法一(效率沒有發揮到極致)
```cpp=
#include <iostream>
using namespace std;
int main()
{
	int arr[5] = {100,2001,12,4,19};
	int n = sizeof arr/ sizeof arr[0];
	int temp = 0;
	for(int i = 0; i < n - 1; i++){
		for(int j = 0; j < n - 1 - i; j++){
			if(arr[j] > arr[j+1]){
				temp = arr[j];
				arr[j] = arr[j+1];
				arr[j+1] = temp;
			}
		}
	}
	
	for(int i = 0; i < 5; i++){
		cout << arr[i] << " ";
	}
    return 0;
} 

```

## 解法二(效率比解法一還要更好)

```cpp=
#include <iostream>
using namespace std;
int main()
{
	int arr[5] = {100,2001,12,4,19};
	int n = sizeof arr/ sizeof arr[0];
	int temp = 0;
	bool flag;
	for(int i = 0; i < n - 1; i++){
		flag = false;
		for(int j = 0; j < n - 1 - i; j++){
			if(arr[j] > arr[j+1]){
				temp = arr[j];
				arr[j] = arr[j+1];
				arr[j+1] = temp;
				flag = true;
			}
		}
		if(flag == false) break;
	}
	
	for(int i = 0; i < 5; i++){
		cout << arr[i] << " ";
	}
    return 0;
} 
```

