插入排序介绍及实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36890813/article/details/88916457

一、插入排序的介绍

  1. 数组分为排好序的部分和没排序的部分,排好序的部分放在前面。
  2. 每i躺选第i个元素放到排好序的部分所对应的位置。

二、Java实现

public class InsertSelect {
	public int[] sort(int[] arr) {
		for (int i = 1; i < arr.length; i++) {//每一趟
			for (int j = i; j > 0; j--) {//第i躺的第i个数据和排好序的部分做比较
				if (arr[j] < arr[j - 1]) {
					int temp = arr[j];
					arr[j] = arr[j - 1];
					arr[j - 1] = temp;
				}else {//比排好序部分最大的数还大就进行下一轮
					break;
				}
			}
		}
		return arr;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_36890813/article/details/88916457