冒泡算法:
public class TestMaopao {
//冒泡排序(从小到大)
public static void main(String[] args) {
int[] arr = {10,9,8,7,6,5,4,3,2,1};
//int arrs[] = new int[]{3,4,4,4,4};
System.out.println("排序前:");
for (int i=0 ; i<10 ; i++){
System.out.print(arr[i]+" ");
}
int temp = 0;
for(int i=0 ; i<10 ; i++)
for (int j=0 ; j<10-i-1 ; j++)
{
if(arr[j] > arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
System.out.println();
System.out.println("排序后:");
for (int i=0 ; i<10 ; i++){
System.out.print(arr[i]+" ");
}
}
//改进的冒泡排序(小->大)
@Test
public void test01(){
int[] array = {9,8,7,6,5,4,3,2,1,0};
System.out.println("排序前:");
for (int i=0 ; i<10 ; i++){
System.out.print(array[i]+" ");
}
int temp = 0;
boolean exchange = false;//做一个标记位
for(int i=0 ; i<10 ; i++){
for (int j=0 ; j<10-i-1 ; j++)
{
if(array[j] > array[j+1]){
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
exchange = true ;//两两进行比较,存在前一位比后一位大的情况exchange变为true
}
}
if (!exchange){//两两进行比较下来发现,如果不存在前一位比后一位大的情况,就说明已经排好序了,break结束程序
break;
}
}
System.out.println();
System.out.println("改进的冒泡排序后:");
for (int i=0 ; i<10 ; i++){
System.out.print(array[i]+" ");
}
}
@Test//从大到小
public void test02(){
int []a = {0,1,2,3,4,5,6,7,8,9};
int len = a.length , temp = 0;
for(int i=0 ; i<len ; i++)
for (int j=0 ; j<len-i-1 ; j++)
{
if(a[j] < a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
for (int i=0 ; i<len ; i++){
System.out.print(a[i]+" ");
}
}
}