1. 程式人生 > >氣泡排序和3個數比較大小思想

氣泡排序和3個數比較大小思想

void bubblesort(int a[])
{
    for(int i=0;i<a.length;i++)
{
for(int j=0;j<a.length-i;j++)
{
    if(a[j]>a[j+1])
{
    temp=a[j];
    a[j]=a[j+1];
    a[j+2]=temp;
}
}
}
    
    }

氣泡排序有兩個迴圈,外迴圈控制趟數,內迴圈找最值,即把最大(最小)的值找出來,找n-1趟就排好序

void sort(int a,int b,int c)
{
     if(a>b)
    {
       t=a;
       a=b;
       b=t;
    }

    if(a>c)
    {
       t=a;
       a=c;
       c=t;
    }
<pre name="code" class="cpp">    if(b>c)
    {
       t=b;
       b=c;
       c=t;
    }
} 先比較a b,交換,再比較a c,交換,這時候a最大了已經,再比較b c,交換,就ok了。