首页 / 算法 / jdk自带的经典算法
jdk自带的经典算法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了jdk自带的经典算法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1942字,纯文字阅读大概需要3分钟。
内容图文
排序
private static void binarySort(Object[] a, int lo, int hi, int start) { assert lo <= start && start <= hi; if (start == lo) start++; for (; start < hi; start++) { // 选择start节点的值为锚点 Comparable pivot = (Comparable) a[start]; // 设置次轮循环排序的左节点为lo, 右节点是start,即次轮将数组索引:lo->start排序好int left = lo; int right = start; assert left <= right; // 锚点pivot的位置,因为之前lo->start-1是排序好,所以通过2分查询找到pivot的位置 // pivot >= all in [lo, left), pivot < all in [right, start).while (left < right) { int mid = (left + right) >>> 1; if (pivot.compareTo(a[mid]) < 0) right = mid; else left = mid + 1; } assert left == right; // 计算数组需要移动的个数,把pivot放到left的位置,后续位置往后挪动一位:left->start-1===>left+1->startint n = start - left; // 优化挪动算法switch (n) { case 2: a[left + 2] = a[left + 1]; case 1: a[left + 1] = a[left]; break; default: System.arraycopy(a, left, a, left + 1, n); } // 将pivot放到left的位置 a[left] = pivot; } }
字符串查找
1 static int indexOf(char[] source, int sourceOffset, int sourceCount, char[] target, int targetOffset, int targetCount, int fromIndex) { 2if (fromIndex >= sourceCount) { 3return (targetCount == 0 ? sourceCount : -1); 4 } 5if (fromIndex < 0) { 6 fromIndex = 0; 7 } 8if (targetCount == 0) { 9return fromIndex; 10 } 11 // 需要查找的第一个字符 12char first = target[targetOffset]; 13int max = sourceOffset + (sourceCount - targetCount); 1415for (int i = sourceOffset + fromIndex; i <= max; i++) { 16/* Look for first character. */17if (source[i] != first) { 18while (++i <= max && source[i] != first); 19 } 2021/* Found first character, now look at the rest of v2 */22if (i <= max) { 23int j = i + 1; 24int end = j + targetCount - 1; 25for (int k = targetOffset + 1; j < end && source[j] 26 == target[k]; j++, k++); 2728if (j == end) { 29/* Found whole string. */30return i - sourceOffset; 31 } 32 } 33 } 34return -1; 35 }
原文:https://www.cnblogs.com/nnavvi/p/12523733.html
内容总结
以上是互联网集市为您收集整理的jdk自带的经典算法全部内容,希望文章能够帮你解决jdk自带的经典算法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。