public static void swap(int[] arr,int a,int b) {
if(arr[a]>arr[b]){
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}
数组中查找问题普通查找
public static void main (String[] args) {
int [] arr = {1,2,3,54,8,7,6};
int index = getIndex(arr,54);
System.out.println(“index=”+index);
}
public static int getIndex(int [] arr, int key) {
for(int i=1;i<arr.length;i++) {
if(arr[i] == key) {
return i;
}
}
return -1;
}
折半查找
第一种方法以要查找的数为条件
public static void main(String[] args) {
int[] arr = {1,2,5,7,8,15,56};
int x = hilfSearch(arr,8);
System.out.println(x);
}
public static int hilfSearch(int[] arr, int key) {
int min = 0;
int max = arr.length;
int mid = (min+max)/2;
while(key != arr[mid]) {
if(key > arr[mid]) {
min = mid+1;
}
else if(key<arr[mid]) {
max = mid-1;
}
if(min>max) {
return -1;
}
mid = (min+max)/2;
}
return mid;
}
第二种方法一最大角标和最小角标做条件
public class dfdfd {
public static void main(String[] args) {
int[] arr = {1,2,5,7,8,15,56};
int x = hilfSearch(arr,56);
System.out.println(x);
}
public static int hilfSearch(int[] arr, int key) {
int min = 0;
int max = arr.length;
int mid;
while (min <= max) {
mid = (min+max)/2;
if(key>arr[mid]) {
min = mid + 1;
}
else if(key<arr[mid]) {
max = mid - 1;
}
else
return mid;
}
return -1;
}
}
十进制转换成2进制
public static void main(String[] args) {
toBin(6);
}
public static void toBin(int a) {
StringBuffer ss = new StringBuffer();
while(a>0) {
ss.append(a%2);
a = a/2;
}
System.out.println(ss.reverse());
}
十进制转换成2进制
查表法
public static void main(String[] args) {
toHex(-6);
}
public static void toHex(int a) {
StringBuffer sb = new StringBuffer();
char[] ch = {'0','1',};
while(a != 0) {
int temp = a&1;
sb.append(ch[temp]);
a = a >>> 1;
}
System.out.println(sb.reverse());
}
十进制转换成16进制
public class dfdfd {
public static void main(String[] args) {
toHex(60);
}
public static void toHex(int a) {
StringBuffer ss = new StringBuffer();
for(int i=1; i<8;i++) {
int temp = a&15;
if(temp>9) {
ss.append((char)(temp-10+'A'));
}
else {
ss.append(temp);
}
a = a >>> 4;
}
System.out.println(ss.reverse());
}
}
十进制转换成16进制第二种方法
public class dfdfd {
public static void main(String[] args) {
toHex(60);
}
public static void toHex(int a) {
StringBuffer ss = new StringBuffer();
while(a>0) {
int temp = a%16;
if(a>9) {
ss.append((char)(temp-10+'A'));
}
else {
ss.append(temp);
}
a = a/16;
}
System.out.println(ss.reverse());
}
}
十进制转换成16进制第三种之查表发
public static void main(String[] args) {
toHex(60);
}
public static void toHex(int a) {
StringBuffer sb = new StringBuffer();
char[] ch = {'0','1','2','3'
,'4','5','6','7'
,'8','9','A','B'
,'C','D','E','F',};
while(a != 0) {
int temp = a&15;
sb.append(ch[temp]);
a = a >>> 4;
}
System.out.println(sb.reverse());
} 作者: 付鹏 时间: 2012-3-11 21:28
靠 格式怎么还有变了的 复制上面来就变形了 = = 还好变得不是太厉害