package com.sxt;
/**
* 二分法详解
*
* @author Administrator
*
*/
public class TwoDemo {
public static void main(String[] args) {
int a[] = { 1, 3, 6, 8, 12, 56, 100 };
int e = ef(a, 2);
System.out.println(e);
}
public static int ef(int a[], int n) {
// 砍半取中间值进行比较
int s = 0, e = a.length - 1;
int m = (s + e) / 2;
while (a[m] != n && e > s) {
// 在前半部分
if (a[m] > n) {
e = m - 1;
}
// 在后半部分
else if (a[m] < n) {
s = m + 1;
}
m = (s + e) / 2;
}
//
if (a[m] == n) {
return m;
} else {
return -1;
}
/**
* 二分法详解
*
* @author Administrator
*
*/
public class TwoDemo {
public static void main(String[] args) {
int a[] = { 1, 3, 6, 8, 12, 56, 100 };
int e = ef(a, 2);
System.out.println(e);
}
public static int ef(int a[], int n) {
// 砍半取中间值进行比较
int s = 0, e = a.length - 1;
int m = (s + e) / 2;
while (a[m] != n && e > s) {
// 在前半部分
if (a[m] > n) {
e = m - 1;
}
// 在后半部分
else if (a[m] < n) {
s = m + 1;
}
m = (s + e) / 2;
}
//
if (a[m] == n) {
return m;
} else {
return -1;
}
}
}
数组工具的使用
public class ArraysDemo {
public static void main(String[] args) {
int a []={1,25,34,88,9,0,-25};
int b []={1,25,34,88,9,0,-25};
// 查询a数组中25这个数的下标
int i = Arrays.binarySearch(a, 25);
System.out.println(i);
// 显示数组的结构和内容
String s = Arrays.toString(a);
System.out.println(s);
// 比较数组内容是否相等
boolean r = Arrays.equals(a, b);
System.out.println(r);
// 将数组按照升序排序
Arrays.sort(a);
System.out.println(Arrays.toString(a));
}
}
冒泡排序
public class BubbleSort
{
public void sort(int[] a)
{
int temp = 0;
for (int i = a.length - 1; i > 0; --i)
{
for (int j = 0; j < i; ++j)
{
if (a[j + 1] < a[j])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
}