冒泡排序+二分法
最近复习课本,看到了这两个简单的算法,就贴出来,冒泡和二分法很简单,不解释 。
1 import java.util.Scanner; 2 3 public class BubblesSortAlgorithm { 4 5 @SuppressWarnings("resource") 6 public static void main(String[] args) { 7 int[] arrs = { 1, 23, 5, 2, 6, 3, 55, 9 }; 8 int i, j, temp = 0; 9 for (i = arrs.length - 1; i > 0; i--) { 10 for (j = 0; j < i; j++) { 11 if (arrs[i] < arrs[j]) { 12 temp = arrs[i]; 13 arrs[i] = arrs[j]; 14 arrs[j] = temp; 15 } 16 } 17 } 18 19 System.out.println("排序后的数组是:"); 20 for (i = 0; i < arrs.length; i++) { 21 System.out.print(" " + arrs[i]); 22 } 23 24 int index = -1, mid = 0, begin = 0, end = arrs.length; 25 Scanner sc = new Scanner(System.in); 26 int num = sc.nextInt(); 27 28 while (begin <= end) { 29 mid = (begin + end) / 2; 30 //System.out.println(mid); 31 if (arrs[mid] == num) { 32 index = mid; 33 break; 34 } else if (arrs[mid] < num) { 35 begin = mid + 1; 36 } else if (arrs[mid] > num) { 37 end = mid - 1; 38 } 39 } 40 if (index == -1) { 41 System.out.println("数字" + num + "不存在"); 42 } else { 43 System.out.println("数字" + num + "在数组中的位置是" + index); 44 45 } 46 } 47 }