import java.util.Random;
public class Sort {
//生成随机数数组
public void init( int[] data ) {
Random rand = new Random();
for ( int i=0; i<data.length; i++ ) {
data[i] = rand.nextInt(100);
}
printRawData( data );
}
//打印原始数据
private void printRawData( int[] data ) {
System.out.println( "\nraw data(len=" + data.length + "):" );
for ( int i=0; i<data.length; i++ ) {
System.out.print( data[i] + " " );
}
System.out.println();
}
//打印排序结果
private void printResultData( String sort, int[] result ) {
System.out.println( sort + " result(len=" + result.length + "):" );
for ( int i=0; i<result.length; i++ ) {
System.out.print( result[i] + " " );
}
System.out.println();
}
//冒泡排序
public void bubbleSort( int[] data ) {
for ( int i=0; i<data.length-1; i++ ) {
for ( int j=0; j<data.length-1-i; j++ ) {
if ( data[j] > data[j+1] ) {
int temp = data[j];
data[j] = data[j+1];
data[j+1] = temp;
}
}
}
printResultData( "bubbleSort", data );
}
//选择排序
public void selectSort( int[] data ) {
int min = data[0];
for ( int i=0; i<data.length; i++ ) {
int minIndex = i;
for ( int j=i+1; j<data.length; j++ ) {
if ( data[j] < data[minIndex] ) {
minIndex = j;
}
}
int temp = data[i];
data[i] = data[minIndex];
data[minIndex] = temp;
}
printResultData( "selectSort", data );
}
//插入排序
public void insertSort( int[] data ) {
for ( int i=1; i<data.length; i++ ) {
for ( int j=i; j>0; j-- ) {
if ( data[j] < data[j-1] ) {
int temp = data[j-1];
data[j-1] = data[j];
data[j] = temp;
}
}
}
printResultData( "insertSort", data );
}
public static void main ( String[] args ) {
Sort sort = new Sort();
int[] a = new int[10];
sort.init( a );
sort.bubbleSort( a );
sort.init( a );
sort.selectSort( a );
sort.init( a );
sort.insertSort( a );
}
}
冒泡排序、选择排序、插入排序(Java实现)
最新推荐文章于 2024-09-10 10:21:38 发布