冒泡排序,顧名思義就像水中的氣泡同樣,氣泡越大,上浮的越快。ios
以整數數組爲例,數值越大的元素咱們就認爲它越應該出如今數組的右邊,這樣就構成了一個遞增數組。c++
對於含有n個元素的數組values,咱們每次從左向右掃描出一個最大的,能夠得知,通過n-1次掃描咱們便可獲得一個有序數組。算法
c++版本:數組
- #include <iostream>
- #include <stdlib.h>
- #include <time.h>
-
- void buddle_sort(int a[], int n)
- {
- for (int i = 0; i < n - 1; ++i)
- for (int j = 0; j < n - i - 1; ++j)
- if (a[j] > a[j + 1])
- {
- int tmp = a[j];
- a[j] = a[j + 1];
- a[j + 1] = tmp;
- }
- }
-
- void print(int a[], int n)
- {
- for (int i = 0; i < n; ++i)
- std::cout << a[i] << " ";
- std::cout << std::endl;
- }
-
- int main()
- {
- ::srand(::time(NULL));
- const int num = 40;
- int a[num] = {0};
- for (int i = 0; i < num; ++i)
- a[i] = ::rand() % 10;
-
- buddle_sort(a, num);
- print(a, num);
- return 0;
- }
#include <iostream>
#include <stdlib.h>
#include <time.h>
void buddle_sort(int a[], int n)
{
for (int i = 0; i < n - 1; ++i)
for (int j = 0; j < n - i - 1; ++j)
if (a[j] > a[j + 1])
{
int tmp = a[j];
a[j] = a[j + 1];
a[j + 1] = tmp;
}
}
void print(int a[], int n)
{
for (int i = 0; i < n; ++i)
std::cout << a[i] << " ";
std::cout << std::endl;
}
int main()
{
::srand(::time(NULL));
const int num = 40;
int a[num] = {0};
for (int i = 0; i < num; ++i)
a[i] = ::rand() % 10;
buddle_sort(a, num);
print(a, num);
return 0;
}
該排序算法是穩定的,時間複雜度是O(n2)spa
附上go語言版本.net
- package main
-
- import "fmt"
- import "math/rand"
- import "time"
-
- func buddle_sort(values []int) {
- for i := 0; i < len(values)-1; i++ {
- for j := 0; j < len(values)-i-1; j++ {
- if values[j] > values[j+1] {
- values[j], values[j+1] = values[j+1], values[j]
- }
- }
- }
- }
-
- func main() {
- values := make([]int, 10)
- fmt.Print(len(values), " ", cap(values), "\n")
- rand.Seed(int64(time.Now().Nanosecond()))
- for i := 0; i < len(values); i++ {
- values[i] = rand.Int() % 10
- }
- buddle_sort(values)
- for _, v := range values {
- fmt.Print(v, " ")
- }
- fmt.Println()
- }