当前位置:   article > 正文

插入排序—Java

插入排序—Java

基本思想 :

  • 实现数组从小到大排
  • 从第二个数开始跟前面的数比较 找到合适的位置插入 后面的数往后推移 但推移不会超过原来插入的数的下标

代码实现

public static void InsertSort(int[] arr) {
		for(int i = 1;i<arr.length;i++) {//从1开始是因为要和前面的数有一个比较的过程
			int InsertIndex=i-1;//要插入的理想目的地
			int Insertvalue= arr[i];
			while (InsertIndex>=0&&Insertvalue<arr[InsertIndex]) {
				//insertindex后移动一位
				arr[InsertIndex+1]=arr[InsertIndex];
				InsertIndex--;
				//一直在减去,所以while结束后代表找到
				//后面要加还给他,代表找到的那个位置
			}
		//
			if(InsertIndex+1!=i) {
				//+1代表找的那个位置
				arr[Insertvalue+1]=Insertvalue;
			}
		}
		for(int i = 0;i<arr.length;i++) {
			System.out.print(arr[i]+"\t");
		}
		
		
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/700643
推荐阅读
相关标签
  

闽ICP备14008679号