氣泡排序(C語言實現)
阿新 • • 發佈:2018-12-31
今天說說氣泡排序演算法。
氣泡排序的思想:就像氣泡一樣讓最小的(或者最大的)浮到最上面,一個個接著浮上來,整個排序完成。
請看圖
這樣一趟排序已完成,此時最小值就會浮到最上面(即水面上)</p><p>這是整個氣泡排序的思想,如果這玩意理解了,那麼程式碼就不難了,至少能看懂了</p><p>宣告,程式碼都是親自敲出來的,GCC版本gcc (Ubuntu 4.4.3-4ubuntu5) 4.4.3Copyright (C) 2009 Free Software Foundation, Inc.This is free software; see the source for copying conditions. There is NOwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
1 #include <stdio.h>
2
3 void Print(int* arr,int len)
4 {
5 int i;
6 for(i=0;i<len;i++)
7 {
8 printf("%d ",arr[i]);
9 }
10 printf("\n");
11 }
12
13 void Swap(int* a,int* b)
14 {
15 *a=*a+*b;
16 *b=*a-*b;
17 *a=*a-*b;
18 }
main.c1 #include "sort.h" 2 3 void Bubble(int* arr,int len); 4 int main(void) 5 { 6 int arr[]={-1,1,-2,2,4}; 7 Print(arr,5); 8 Bubble(arr,5); 9 Print(arr,5); 10 return 0; 11 } 12 13 void Bubble(int* arr,int len) 14 { 15 int i,j; 16 for(i=0;i<len;i++) 17 { 18 for(j=len-1;j>i;j--) //從最深處開始,為什麼j>i?這是因為i表示位置,i=0表示正在排序第一個位置,如果這個位置拍好了,下次就是排序i=1位置 19 { 20 if(arr[j]>arr[j-1]) 21 Swap(&arr[j],&arr[j-1]); //交換值 22 } 23 } 24 }
完整程式碼實現地址下載:http://download.csdn.net/detail/mingyueruya/8188677