java 冒泡排序的實現java
1 public class BubbleTest { 2 3 public static void sort(int[] a){ 4 5 for(int i = 0;i < a.length - 1;i++){ 6 7 for(int j = 0;j < a.length - i -1;j++){ 8 9 if(a[j] > a[j+1]){ 10 11 int temp = a[j]; 12 a[j] = a[j+1]; 13 a[j+1] = temp; 14 } 15 } 16 } 17 18 for(int k = 0;k < a.length;k++){ 19 20 System.out.println(a[k]); 21 } 22 } 23 24 public static void main(String[] args) { 25 26 int[] a = {1,33,44,2,22,47,35,67,54}; 27 sort(a); 28 } 29 }
java的二分查找的實現spa
public class BinarySeacher { public static int binarySeacher(int[] a,int b){ int low = 0; int high = a.length - 1; int middle = 0; while(low <= high){ middle = (low + high) / 2; if(b == a[middle]){ return middle; } else if(b < a[middle]){ high = middle - 1; } else{ low = middle + 1; } } return -1; } public static void main(String[] args) { int[] a = {55,66,33,2,77,8,9}; int result = binarySeacher(a, 9); System.out.println(result); } }