1. 程式人生 > >java 之冒泡排序

java 之冒泡排序

i++ 比較 body time public eat 冒泡 scanner pos

冒泡排序:可以想象成煮開水,氣泡在瓶底的時候是比較小的,到達水面的時候達到最大。

冒泡排序的思想:先確定是升序還是降序,這裏升序為例。每兩個相鄰的數字進行比較,前一個數字比後面一個數字大,就將兩個數字交換位置,否則位置不變繼續下一個。一輪排序之後,數組中最大的數字一定是在最後。

偽代碼:

    數組a={10,9,8,7,6,5,4,3,2,1}

      for(int i=0;i<a.length;i++){

          for(int j=0;j<a.length-i-j;j++){ //為什麽是j<a.length-i-1; 先解釋減1,到數據組的最後兩個數的時候a[j] 和 a[j++] 進行比較,當沒有減1的時候會下標越界。為什麽要減i,每一輪排序都會產生(i+1)個已經排好序的數據

              交換數據:swap(a[j],a[j++])

                      }

          }

      輸出排序完的數據:升序

代碼:

package math;

/**
 * Created by Administrator on 2018/3/2.
 * 冒泡排序
 * 思想:冒泡排序就是將相鄰的兩個相比較,按照定義的規則,決定將大數放在前面還是後面,然後進行交換順序,
 *       每一次排序都會將那一次最大的或者最小的數排在最後
 *        冒泡排序的時間復雜度:o(n2)
 */
public class BubbleTest {




    
public static void main(String[] args){ /* //控制臺進行輸入數據 Scanner s=new Scanner(System.in); //輸入的數字存放到數組中 Integer array[]=new Integer[10]; Integer count=0; System.out.println("請輸入十個數:"); while (s.hasNextInt()){ Integer tempNum=s.nextInt(); array[count++]=tempNum; if(count>9){ break; } } System.out.println("輸入的十個數是:"); for(int i=0;i<10;i++){ System.out.print(array[i]+","); }
*/ Integer count=100000; Integer array[]=new Integer[count]; for(int w=0;w<array.length;w++){ array[w]=count--; } /*冒泡排序*/ long startTime=System.currentTimeMillis(); System.out.println(startTime); for(Integer i=0;i<array.length;i++){ for(Integer j=0;j<array.length-i-1;j++){ if(array[j]>array[j+1]){ Integer temp; temp=array[j]; array[j]=array[j+1]; array[j+1]=temp; } } /* System.out.println("第"+i+"次排序之後的順序:"); for(Integer k=0;k<array.length;k++){ System.out.print(array[k]+","); }*/ } Long endTime=System.currentTimeMillis(); System.out.println(endTime); System.out.println("總耗時==="+(endTime-startTime)); /* System.out.println("排序之後的順序:"); for(Integer f=0;f<array.length;f++){ System.out.print(array[f]+","); } */ } }

java 之冒泡排序