Java数据结构及算法实例:插入排序 Insertion Sort
更新时间:2015年06月20日 11:22:34 投稿:junjie
这篇文章主要介绍了Java数据结构及算法实例:插入排序 Insertion Sort,本文直接给出实例代码,代码中包含详细注释,需要的朋友可以参考下
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud)
(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun)
/** * 选择排序的思想: * 每次循环前,数组左边都是部分有序的序列, * 然后选择右边待排元素,将其值保存下来 * 依次和左边已经排好的元素比较 * 如果小于左边的元素,就将左边的元素右移一位 * 直到和最左边的比较完成,或者待排元素不比左边元素小 */ package al; public class InsertionSort { public static void main(String[] args) { InsertionSort insertSort = new InsertionSort(); int[] elements = { 14, 77, 21, 9, 10, 50, 43, 14 }; // sort the array insertSort.sort(elements); // print the sorted array for (int i = 0; i < elements.length; i++) { System.out.print(elements[i]); System.out.print(" "); } } /** * @author * @param array 待排数组 */ public void sort(int[] array) { // min to save the minimum element for each round int key; // save current element for(int i=0; i<array.length; i++) { int j = i; // current position key = array[j]; // compare current element while(j > 0 && array[j-1] > key) { array[j] = array[j-1]; //shift it j--; } array[j] = key; } } }
相关文章
SpringMVC中Invalid bound statement (not f
本文主要介绍了SpringMVC中Invalid bound statement (not found)常见报错问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2023-05-05基于Java并发容器ConcurrentHashMap#put方法解析
下面小编就为大家带来一篇基于Java并发容器ConcurrentHashMap#put方法解析。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-06-06
最新评论