거품 정렬 알고리즘 (C & 자바 구현)

C 언어 판
#include <stdio.h>

#define SWAP( a, b ) { t = a; a = b; b = t; }
#define LESS( a, b ) a < b

void disp_array( int a[], int n );

void bubble_sort( int a[], int n )
{
    int i, j, t;
    int flag = 1; // 本趟比较中是否发生了交换?
    for( i = 0; i < n - 1 && flag == 1; ++i )
    {
        flag = 0;
        for( j = 0; j < n - i - 1; ++j )
        {
            if( LESS( a[j + 1], a[j] ) )
            {
                flag = 1;
                SWAP( a[j + 1], a[j] );
            }
        }
        printf( "Round %2d: ", i + 1 );
        disp_array( a, n );
    }
}

void disp_array( int a[], int n )
{
    int i;
    for( i = 0; i < n; ++i )
        printf( "%d ", a[i] );
    printf( "
" ); } int main() { int i, n = 8; int a[] = { 49, 38, 65, 97, 76, 13, 27, 49 }; printf( "Before sorting: " ); disp_array( a, n ); bubble_sort( a, n ); printf( "After sorting: " ); disp_array( a, n ); return 0; }

자바 언어 버 전
public class TestBubbleSort {
	
	public static void dispArray( int a[] ) {
		for( int i = 0; i < a.length; ++i )
			System.out.print( a[i] + " " );
		System.out.println();
	}
	
	public static void swap( int a[], int i, int j ) {
		int t = a[i]; a[i] = a[j]; a[j] = t;
	}
	
	public static boolean less( int a[], int i, int j ) {
		return a[i] < a[j];
	}
	
	public static void bubbleSort( int [] a ) {
		boolean change = true;
		for( int i = 0; change && i < a.length - 1; ++i ) {
			change = false;
			for( int j = 0; j < a.length - i - 1; ++j ) {
				if( less( a, j + 1, j ) ) {
					change = true; 
					swap( a, j + 1, j );
				}
			}
			System.out.print( "Round " + ( i + 1 ) + ": " );
			dispArray( a );
		}
	}
	
	public static void main( String[] args ) {
		int a[] = { 100, 49, 38, 65, 97, 76, 13, 27, 49 };
		System.out.print( "Before sorting: " );
		dispArray( a );
		
		bubbleSort( a );
		
		System.out.print( "After sorting: " );
		dispArray( a );
	}
}

좋은 웹페이지 즐겨찾기