给出一组数据并进行排序,直接插入排序与折半插入排序示例

 1 package javaproject;
 2 public class ZhijiePaixu {    
 3     void insertSort(int a[])
 4     {
 5         int i,j,k;
 6         int n=a.length;
 7         for(i=1;i<n;i++)
 8         {
 9             for(j=i-1;j>=0;j--)
10                 if(a[j]<a[i])
11                     break;
12                 if(j!=i-1)
13                 {
14                     int temp=a[i];
15                     for(k=i-1;k>j;k--)
16                         a[k+1]=a[k];
17                     a[k+1]=temp;
18                 }
19         }
20     }
21     public static void main(String[] args) {
22         // TODO Auto-generated method stub
23         int a[]={12,2,26,7,8,11};
24         ZhijiePaixu b=new ZhijiePaixu();
25         System.out.println("排序前:"+a[0]+" "+a[1]+" "+a[2]+" "+a[3]+" "+a[4]+" "+a[5]);
26         b.insertSort(a);
27         System.out.println("排序后:"+a[0]+" "+a[1]+" "+a[2]+" "+a[3]+" "+a[4]+" "+a[5]);
28     }
29 
30 }

 

package javaproject;

public class ZheBanPaixu {

    void insertSort(int a[])
    {
        int low,high,m,k;
        int n=a.length;
            for(int i=1;i<n;i++)
            {    low=0;high=n-1;
                while(low<=high)
                {
                    m=(low+high)/2;
                    if(a[m]<a[i])
                        low=m+1;
                    else
                        high=m-1;
                }
                if(high+1!=i-1)
                {
                    int temp=a[i];
                    for(k=i-1;k>high+1;k--)
                        a[k+1]=a[k];
                        a[k+1]=temp;
                }
            }
        }
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            int a[]={12,2,26,7,8,11};
            ZhijiePaixu b=new ZhijiePaixu();
            System.out.println("排序前:"+a[0]+" "+a[1]+" "+a[2]+" "+a[3]+" "+a[4]+" "+a[5]);
            b.insertSort(a);
            System.out.println("排序后:"+a[0]+" "+a[1]+" "+a[2]+" "+a[3]+" "+a[4]+" "+a[5]);
        }

    }

 

 

posted on 2018-03-19 23:15  小星_log  阅读(437)  评论(0编辑  收藏  举报