主旨: [programming] Bubble Sort 與 Shell Sort 效 率 比 較    新聞組: comp.web
 寄件者: "rimring"    日期: 1 Aug 2004 05:42:45 +0800
 
 
Bubble Sort 與 及 Shell Sort 都 是 其 中 一 種 internal sorting 技 術 。
增 加 n 的 值 可 輸 入 更 多 參 數 。
初 步 測 試 顯 示 Shell Sort 的 效 率 比 Bubble Sort 高 。
----------------------------------------------------------------------------
----
程 式 編 碼
----------------------------------------------------------------------------
----
/* compare bubble sort with shell sort
   designed by Tong on 20/4/98 */

#include<stdio.h>
#define n 20

void swap(int *a, int *b)
{
 int temp;
 temp=*a;
 *a=*b;
 *b=temp;
 }

int re(int k)
{ if (k==1) return 0;else
  if (k==2) return 1;else
  return (k-1+re(k-1)); };


void main ()
{int i,j,c2=0,exit_flag=0;

int a[n]={1,21,0,47,60,15,84,65,77,88,100,93,8,17,36,5,24,63,72,20};
int s[n];

// start of bubble sort
for(i=0;i<n;i++){s[i]=a[i];}
printf("bubble sort :\nbefore sorted : ");
for (i=0;i<n;i++) {printf("%d ",a[i]);}
printf("\n");

for(i=1; (i<=n-1)&&(exit_flag==0); i++)
{exit_flag=1;
for (j=1;j<=n-i;j++)
    {if (a[j-1]>a[j+1-1])
     {swap(&a[j-1],&a[j+1-1]);
      c2++;
      exit_flag=0; }
     }
}

printf("after  sorted : ");
for (i=0;i<n;i++) {printf("%d ",a[i]);}
printf("\nbubble sort: no. of swap =%4d",c2);

// start of shell sort
i=c2=0;
int inc=n,x;
printf("\n\nshell  sort :\nbefore sorted : ");
for (i=0;i<n;i++) {printf("%d ",s[i]);}
printf("\n");

while (inc>=2){
inc=inc/2;
for(i=0;i<=n-1-inc;i++)
{if (s[i]>s[i+inc]) {swap(&s[i],&s[i+inc]);c2++;
x=i;
while ((x>=inc)&&((s[x-inc]>s[x])))
{swap(&s[x-inc],&s[x]);c2++;
x=x-inc;}//end while
}//end if
};//end for
}//end while

printf("after  sorted : ");
for (i=0;i<n;i++) {printf("%d ",s[i]);}
printf("\nshell  sort:no. of swap =%4d",c2);
printf("\n--- end of program ---\n\n");
}

----------------------------------------------------------------------------
----
Sample Output
----------------------------------------------------------------------------
----

bubble sort :
before sorted : 1 21 0 47 60 15 84 65 77 88 100 93 8 17 36 5 24 63 72 20
after  sorted : 0 1 5 8 15 17 20 21 24 36 47 60 63 65 72 77 84 88 93 100
bubble sort: no. of swap =  81

shell  sort :
before sorted : 1 21 0 47 60 15 84 65 77 88 100 93 8 17 36 5 24 63 72 20
after  sorted : 0 1 5 8 15 17 20 21 24 36 47 60 63 65 72 77 84 88 93 100
shell  sort:no. of swap =  33
--- end of program ---







--
歡迎任何人仕申請開news://nntp.cn/apply