首页 > 代码库 > 二分查找
二分查找
1 package com.wh.ObjectHomeWork; 2 3 import java.util.Arrays; 4 5 public class CharArray { 6 private char[] words; 7 8 public CharArray(char[] words) { // 构造方法 9 this.words = words;10 }11 12 public void sort() { // 对数组进行冒泡排序13 for (int i = 0; i < words.length - 1; i++) {14 for (int j = 0; j < words.length - 1 - i; j++) {15 if (words[j] > words[j + 1]) {16 char t = words[j];17 words[j] = words[j + 1];18 words[j + 1] = t;19 }20 }21 }22 }23 24 public int search(char key){25 int start=0,ends=words.length-1;26 int middle;27 int index=0;28 for(;;){29 middle=(ends+start)/2+(ends+start)%2;30 if(words[middle]==key){31 index=middle;32 break;33 }else if(key<words[middle]&&key>=words[start]){34 ends=middle;35 }else if(key>words[middle]&&key<=words[ends]){36 start=middle;37 }else{38 index=-1;39 break;40 }41 System.out.print(index+",");42 } 43 return index;44 }45 46 public static void main(String[] args) {47 char[] arr = "qwertyuiopasdfghjklzxcvbnm".toCharArray();48 CharArray c1 = new CharArray(arr);49 System.out.println("排序前:" + Arrays.toString(arr));50 c1.sort();51 System.out.println("排序后:" + Arrays.toString(arr));52 char num=150;53 int index=c1.search(num);54 System.out.println(index);55 }56 }
1 排序前:[q, w, e, r, t, y, u, i, o, p, a, s, d, f, g, h, j, k, l, z, x, c, v, b, n, m]2 排序后:[a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]3 -1
二分查找
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。