代码改变世界

Java数组4(2015-8-27)

2015-08-27 14:01  马尔代夫_珍  阅读(179)  评论(0编辑  收藏  举报

1、插入排序法(用的比较少)。

public class InsertSort{      

   public static void main(String [] args){

                int [] array={2,6,3,9,5,22,19,26,11};           

               for(int i=1;i<array.length;i++){                   

                           int temp=array[i];                    

                           int j=i;//把下标保存起来                  

                           while(j>0&&temp<array[j-1]){                    

                                           //上面的数覆盖其下面的数

                                       array[j]=array[j-1];                        

                                       j--;                    

                          }                    

                          array[j]=temp;//插入数据         

               }                

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

                          System.out.print(array[i]+" ");           

               }  

}}

2、选择排序法(从数组当中找出最大的或最小的数据进行一一比较)

public class SelectSort{      

public static void main(String [] args){

              int [] array={1,5,4,6,8,90,45,22,87,212,447};          

              int min=0;           

             for(int i=0;i<array.length-1;i++){                 

                        min=i;//先默认第一个是最小的。                 

                       for(int j=i+1;j<array.length;j++){                           

                                if(array[min]>array[j]){                               

                                           min=j;                           

                                 }            

                      }                   

                      // 如果第i个最小的数位置不在i上,则进行交换                 

                     if(i!=min){                   

                            int temp=array[i];                   

                            array[i]=array[min];                 

                            array[min]=temp;                

                        }              

              }           

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

                            System.out.print(array[i]+" ");            

             }

}}