zoukankan      html  css  js  c++  java
  • 直接插入排序---java实现

    思路:遍历无序的原数组,把第i个的后一个即i+1去与前面的i个逐个比较...

    解法一:

    package com.sheepmu.text;
    
    import java.util.Arrays;
      /*   
      * @author sheepmu
      */ 
    public class Sort {
    	 public static void main(String[] args){
    		 int[] arr={64,5,7,89,6,24};
    		 insertSort(arr);
    		 System.out.println(Arrays.toString(arr));
    	 }	 	 
    	 public static void insertSort(int[] arr){
    		 int len=arr.length;
    		 int temp=0;
    		 for(int i=0;i<len-1;i++){//要len-1,不然后面i+1要越界。
    			  temp=arr[i+1];	 
    			  for(int  j=i;j>=0;j--){
    				  if(temp<arr[j]){
    					  arr[j+1]=arr[j];
    					  arr[j]=temp;
    					  }
    			  }
    			 
    		 }
    	 }
    }	 
     
    解法二:

    package com.sheepmu.text;
    
    import java.util.Arrays;
      /*   
      * @author sheepmu
      */ 
    public class Sort {
    public static void main(String[] args){
    int[] arr={64,5,7,89,6,24};
    insertSort(arr);
    System.out.println(Arrays.toString(arr));
    }  
    public static void insertSort(int[] arr){
    int len=arr.length;
    int j,temp=0;
    for(int i=0;i<len-1;i++){//要len-1,不然后面i+1要越界。
     temp=arr[i+1];
     j=i;
     while(j>=0&&temp<arr[j]){
     arr[j+1]=arr[j];
      j--;
     }
     arr[j+1]=temp;//因为上面运行完了后j--咯,所以这里是arr[j+1]=temp;而不是arr[j]=temp;
    }
    }
    }  
     
    


  • 相关阅读:
    熟悉常用的HBase操作
    爬虫大作业
    熟悉常用的HDFS操作
    数据结构化与保存
    获取全部校园新闻
    爬取校园新闻首页的新闻的详情,使用正则表达式,函数抽离+网络爬虫基础练习
    中文词频统计
    英语词频统计
    AXIOS中文文档
    overload方法重载
  • 原文地址:https://www.cnblogs.com/oversea201405/p/3766906.html
Copyright © 2011-2022 走看看