資料結構——氣泡排序
阿新 • • 發佈:2018-12-19
氣泡排序原理
比如要對n個數進行氣泡排序,用兩個for迴圈,外層迴圈控制迴圈次數,內層迴圈從第一個位置開始相鄰兩個數進行比較,如果前面的數大就交換否則不交換,就這樣一直進行比較直到比到最後一個數為止。然後你會發現n個數裡最大的數已經被移到最後位置了。比如下面這個陣列:
5 |
12 |
41 |
14 |
21 |
13 |
19 |
7 |
44 |
29 |
經過一次氣泡排序過後:
5 |
12 |
41 |
14 |
21 |
13 |
19 |
7 |
44 |
29 |
5 |
12 |
41 |
14 |
21 |
13 |
19 |
7 |
44 |
29 |
5 |
12 |
14 |
41 |
21 |
13 |
19 |
7 |
44 |
29 |
5 |
12 |
14 |
21 |
41 |
13 |
19 |
7 |
44 |
29 |
5 |
12 |
14 |
21 |
13 |
41 |
19 |
7 |
44 |
29 |
5 |
12 |
14 |
21 |
13 |
19 |
41 |
7 |
44 |
29 |
5 |
12 |
14 |
21 |
13 |
19 |
7 |
41 |
44 |
29 |
5 |
12 |
14 |
21 |
13 |
19 |
7 |
41 |
44 |
29 |
5 |
12 |
14 |
21 |
13 |
19 |
7 |
41 |
29 |
44 |
這樣就將最大的數排在了最後面,簡單的原理大致就是這樣,至於細節我們還是通過程式碼來觀察。
氣泡排序程式碼
#include <iostream>
using namespace std;
#define SIZE 10
void Swap(int *p1, int *p2); //交換兩個數
void BubbleSort(int arry[], int size); //氣泡排序
int main()
{
int arry[SIZE] = { 52, 48, 65, 40, 12, 51, 99, 78, 58, 68 };
BubbleSort(arry, SIZE);
for (int i = 0; i < SIZE; i++)
cout << arry[i] << " ";
cout << endl;
system("pause");
return 0;
}
void Swap(int *p1, int *p2)
{
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
void BubbleSort(int arry[], int size)
{
for (int i = 0; i < size - 1; i++) //控制迴圈次數
{
for (int j = 0; j < size - 1; j++) //將最大的數移到最後面
{
if (arry[j]>arry[j + 1])
Swap(&arry[j], &arry[j + 1]);
}
}
}
大家看看這個程式碼是不是還有改進的地方呢?比如到遇到一個本來已經排好序的陣列,是不是還是要迴圈n-1次呢?下面是改進後的程式碼。
#include <iostream>
using namespace std;
#define SIZE 10
void Swap(int *p1, int *p2); //交換兩個數
void BubbleSort(int arry[], int size); //氣泡排序
int main()
{
int arry[SIZE] = { 52, 48, 65, 40, 12, 51, 99, 78, 58, 68 };
BubbleSort(arry, SIZE);
for (int i = 0; i < SIZE; i++)
cout << arry[i] << " ";
cout << endl;
system("pause");
return 0;
}
void Swap(int *p1, int *p2)
{
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
void BubbleSort(int arry[], int size)
{
for (int i = 0; i < size - 1; i++) //控制迴圈次數
{
int flag = 0;
for (int j = 0; j < size - 1; j++) //將最大的數移到最後面
{
if (arry[j]>arry[j + 1])
{
flag = 1;
Swap(&arry[j], &arry[j + 1]);
}
}
if (flag == 0)//如果flag=0則沒有交換 說明整個陣列已經排好序就不用再繼續迴圈直接退出
return;
}
}
PS:這是博主第一次發表文章,想通過這樣的方式來複習一下以前學習的知識並分享給大家,如果有什麼做的不好的地方歡迎留言哈,之後一定改進。