首页 > 代码库 > 冒泡排序两种方法(从头到尾 和从尾到头扫描 )

冒泡排序两种方法(从头到尾 和从尾到头扫描 )

 

int bubbleSort1(int* array,int len )
{
    int i ,j,temp;
    i = j  = temp = 0;
    for(  i = 0;  i < len - 1;i++ )
    {
        for(j = len -1 ;j > i;j-- )
        {
            if( array[j-1] > array[j] )
            {
                temp = array[j-1];
                array[j-1] = array[j];
                array[j] = temp;
            }
        }
    }
    return 0;
}

int bubbleSort2(int* array,int len )
{
    int i ,j,temp;
    i = j  = temp = 0;
    for( i = 0 ; i < len - 1; i++ )
    {
        for( j = 0; j < len - i -1;j++ )
        {
            if( array[j+1] < array[j] )
            {
                temp = array[j+1];
                array[j+1] = array[j];
                array[j] = temp;
            } 
        }
    }


    return 0;
}



int main(int argc, char* argv[])
{
    int i = 0;
    int a[]={1,43,2,5,10,99,35,34,65,3,7,37,25,89,99};
    int b[sizeof(a)/sizeof(a[0])];
    memcpy(&b,&a,sizeof(a));
    bubbleSort1(a,sizeof(a)/sizeof(a[0]));
    bubbleSort2(b,sizeof(b)/sizeof(b[0]));
    for( i = 0 ; i < sizeof(a)/sizeof(a[0]);i++ )
    {
        printf("%d ",a[i]);
    }
    printf("\n");
    for( i = 0 ; i < sizeof(b)/sizeof(b[0]);i++ )
    {
        printf("%d ",b[i]);
    }
    printf("\n");

    return 0;
}

 

冒泡排序两种方法(从头到尾 和从尾到头扫描 )