当前位置 : 主页 > 编程语言 > java >

冒泡排序+二分查找

来源:互联网 收集:自由互联 发布时间:2021-06-28
冒泡排序+二分查找,基础版 public class Test { public static void main(String[] args) { //查找数组 a 中是否包含元素 s int[] array = {56,78,54,12,7,1,8,5,2,425,41,66,6,9,3}; int s = 56; paiXu(array);//冒泡排序 boolean
冒泡排序+二分查找,基础版
public class Test {
     
     public static void main(String[] args) {
          //查找数组 a 中是否包含元素 s
          int[] array = {56,78,54,12,7,1,8,5,2,425,41,66,6,9,3};
          int s = 56;
          paiXu(array);//冒泡排序
          boolean result = search(array, s);//二分查找
          System.out.println(result);
     }
     
     public static int[] paiXu(int[] array) {
          int p = 0;
          for(int i = 1;i < array.length;i++){
              for(int j = 0;j <(array.length - i);j++){
                   if (array[j] > array[j+1]) {
                        p = array[j];
                        array[j] = array[j + 1];
                        array[j + 1] = p;
                   }
              }
          }
          return array;
     }
     
     public static boolean search(int[] array,int s) {
          int left = 0;
          int right = array.length - 1;
          int mid = (left + right) / 2;
          while(right >= left){
              if (array[mid] == s) {
                   return true;
              }else if (array[mid] > s) {
                   right = mid - 1;
              }else {
                   left = mid + 1;
              }
              mid = (left + right) / 2;
          }
          return false;
     }
}
网友评论