[算法] 插入排序,直接插入

来源:互联网 发布:大数据时代txt微盘 编辑:程序博客网 时间:2024/05/18 18:14

算法水平简直不忍直视了,笨鸟先飞,还是默默地练习吧。

插入排序算法,直接插入。

算法思路整理:

把一个序列分为前后两部分,前部分是已经排好序的,后部分是待排序,首先,前部分只有一个元素,肯定可以认为是有序的,然后从后部分的数据中依次插入到前部分,插入到正确位置,遍历完后面全部数据,完成排序。


测试源码:

/** * 算法训练 */package com.gopain.main;/** * @author gopain 插入排序 基本思路: 将序列的第一个数作为一个有序序列,然后从第二个开始遍历,分别插入到有序序列中。 */public class InsertSort {public static final boolean SORT_DESC = true;public static final boolean SORT_ASC = false;/** * @param args */public static void main(String[] args) {int[] datas = { 2, 3, 1, 4, 6, 12, 43, 2, 1, 2, 312, 23, 54, 65, 76,55, 44, 23, 55, 34, 343, 23, 321 };// InsertSort.sort(datas, 23, InsertSort.SORT_ASC);//排序,从0到23InsertSort.sort(datas, 0, 15, InsertSort.SORT_ASC);//排序从0到15// InsertSort.sort(datas, InsertSort.SORT_ASC);//全部排序for (int i = 0; i < datas.length; i++) {System.out.print(datas[i] + ",");}}/** * 部分排序 *  * @param datas * @param end *            结束位置 * @param sortDesc *            是否降序 */private static void sort(int[] datas, int end, boolean sortDesc) {if (null == datas || end > datas.length)return;if (sortDesc)// 降序排列coreSortDESC(datas, 0, end);else// 升序排列coreSortASC(datas, 0, end);}/** * 部分排序 *  * @param datas * @param begin *            排序起始位置 * @param end *            排序结束位置 * @param sortDesc *            是否降序排列 */private static void sort(int[] datas, int begin, int end, boolean sortDesc) {if (null == datas || end > datas.length || 0 > begin)return;if (sortDesc)// 降序coreSortDESC(datas, begin, end);else// 升序coreSortASC(datas, begin, end);}/** * 传入需要排序处理的数据,全部排序 *  * @param datas * @param desc *            是否升序排列 */private static void sort(int[] datas, final boolean desc) {int len = 0;if (null == datas || 0 == (len = datas.length))return;if (desc)// 降序排列coreSortDESC(datas, 0, len);elsecoreSortASC(datas, 0, len);}private static void coreSortASC(int[] datas, int begin, int end) {for (int i = begin + 1; i < end; i++) {if (datas[i] < datas[i - 1]) {// 如果datas[i] >// datas[i-1]直接插入,升序排列int tem = datas[i];// 提取当前值datas[i] = datas[i - 1];// 后移一位有序序列,为当前值腾出一个插入的位置int j = i - 1;// 有序序列位置while (datas[j] > tem) {// 找到有序序列中tem的位置datas[j + 1] = datas[j];j--;if (j < 0)break;}datas[j + 1] = tem;// 插入当前值到有序列的位置}}}private static void coreSortDESC(int[] datas, int begin, int end) {for (int i = begin + 1; i < end; i++) {if (datas[i] > datas[i - 1]) {// 如果datas[i] >// datas[i-1]直接插入,降序排列int tem = datas[i];// 提取当前值datas[i] = datas[i - 1];// 后移一位有序序列,为当前值腾出一个插入的位置int j = i - 1;// 有序序列位置while (datas[j] < tem) {// 找到有序序列中tem的位置datas[j + 1] = datas[j];j--;if (j < 0)break;}datas[j + 1] = tem;// 插入当前值到有序列的位置}}}}


0 0
原创粉丝点击