Java中的冒泡排序法and针对数组的普通查找法和二分查找法
2012-03-09 17:06
281 查看
下面是冒泡排序法的示例代码
下面是针对数组的普通查找法和二分查找法的示例代码
package com.jadyer.sort; /** * 冒泡排序法 * @see JDK本身也提供了数组排序API,不妨参考一下,即Arrays.sort(array) */ public class BubbleSort { public static void main(String[] args) { bubbleSort(new int[]{4,6,9,8,3,2}); } public static void bubbleSort(int[] array){ for(int i=0; i<array.length-1; i++){ for(int j=0; j<array.length-i-1; j++){ if(array[j] > array[j+1]){ int temp = array[j]; array[j] = array[j+1]; array[j+1] = temp; } } System.out.print("这是第" + (i+1) + "次排序,排序结果为: "); for(int k=0; k<array.length; k++){ System.out.print(array[k] + " "); } System.out.println(); } } }
下面是针对数组的普通查找法和二分查找法的示例代码
package com.jadyer.sort; /** * 数组查找方式 * @detail 这里演示了普通查找法和二分查找法 */ public class ArraySearch { public static void main(String[] args) { int commonResult = commonSearch(new int[]{1,5,6,7,4,3,9,11,13,14,16,19,21}, 9); int binaryResult = binarySearch(new int[]{1,3,4,6,7,8,9,12,15,17,18,20,22}, 8); System.out.println("二分查找法: " + binaryResult); System.out.println("普通查找法: " + commonResult); } /** * 普通查找法 * @detail 该方式最好理解,同时效率也最低 */ public static int commonSearch(int[] array, int value){ for(int i=0; i<array.length; i++){ if(value == array[i]){ return i; //返回该元素在数组中的下标 } } return -1; //不存在该元素则返回-1 } /** * 二分查找法 * @detail 要求数组有序,升序或降序均可 */ public static int binarySearch(int[] array, int value){ int low = 0; //最小元素值的下标 int high = array.length - 1; //最大元素值的下标 int middle; //中间元素的下标 while(low <= high){ middle = (low+high) / 2; for(int i=0; i<array.length; i++){ System.out.print(array[i]); if(i == middle){ System.out.print("#"); //在元素后面用#号标识其为中间元素 } System.out.print(" "); //各元素间用空格隔开 } System.out.println(); if(value == array[middle]){ return middle; } if(value < array[middle]){ high = middle - 1; //右侧的不要了 } if(value > array[middle]){ low = middle + 1; //左侧的不要了 } } return -1; //不存在该元素则返回-1 } }
相关文章推荐
- 【排序】冒泡排序法and针对数组的普通查找法和二分查找法
- 【排序】冒泡排序法and针对数组的普通查找法和二分查找法
- Java针对数组的普通查找法和二分查找法
- 在JS的(字符串)数组中针对每个元素的内容进行查找和替换
- Java二分法在已排序数组中查找指定数
- JAVA中给数组动态赋值及在数组中查找数据
- Java 查找某个数字在数组中第一次和最后一次出现的位置
- Java常用类库——Arrays类(用于普通数组操作)、比较器(Comparable、Comparator 用于对象排序)的使用
- java数组-顺序插入数据及二分法查找数据
- java语言编写的数组冒泡排序法
- Java数组的几种常用操作方法(排序算法及查找)
- 【Java】数组二分查找元素
- java基础--常用数组的一些操作方法-查找-最值-排序
- Java基础05-数组排序与查找
- java学习记录——数组查找(在数组中查找并输出你所需要的数据)
- Java 在数组中查找
- 黑马程序员 java基础 函数 数组 查找与排序总结
- java基础-使用Arrays管理数组排序,复制,查找,填充
- 遍历查找集合或者数组中的某个元素的值 java代码 详解 Android开发
- 黑马程序员--数组的排序和查找--java学习日记2(基础知识)