1、数组排序,冒泡排序法
package arraytest;
public class ArraySort {
public static void bubbleSort(int[] array) {
int len = array.length - 1;
for (int i = 0; i < len; i++) {
for (int j = 0; j < len - i; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
print(i + 1, array);
}
}
public static void print(int time, int[] array) {
System.out.println("第" + time + "次排序");
int len = array.length;
for (int i = 0; i < len; i++) {
System.out.print(array[i]);
}
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
int[] array = new int[] { 5, 4, 6, 9, 2, 7 };
bubbleSort(array);
}
}
输出结果:
第1次排序
456279第2次排序
452679第3次排序
425679第4次排序
245679第5次排序
245679
2、数组二叉查找算法(前提示数组已排好序)
package arraytest;
/**
*
* @author jinpp 数组的二叉查找算法
*/
public class ArrayFinder {
public static int indexof(int[] array, int value) {
int low = 0;// 低位
int high = array.length - 1;// 高位
int middle;// 中间位置
while (low < high) {
middle = (low + high) / 2;// 3
print(array, middle);
if (array[middle] == value)
return middle;
if (array[middle] > value) {
// 前半部分
high = middle;
} else if (array[middle] < value) {
// 后半部分
low = middle;
}
}
return -1;
}
public static void print(int[] array, int middle) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
if (i == middle)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
public static void main(String[] args) {
int[] array = new int[] { 4, 5, 6, 7, 9, 13, 17 };
// 查找13在数组array中的位置
System.out.println("location of 13 :" + indexof(array, 13));
}
}
输出结果:
4 5 6 7*9 13 17
4 5 6 7 9*13 17
4 5 6 7 9 13*17
location of 13 :5
3、数组实用类:Arrays
package arraytest;
import java.util.Arrays;
public class ArraysTester {
public void testStringArray() {
String[] s1 = { "Tom", "Jack", "Mike", "Marry", "Tom2" };
String[] s2 = { "Tom", "Jack", "Mike", "Marry", "Tom2" };
System.out.println("s1是否等于s2:" + Arrays.equals(s1, s2));
Arrays.sort(s1);
System.out.println("排序后的s1是否等于s2:" + Arrays.equals(s1, s2));
System.out.println("Tom在s1中的位置:" + Arrays.binarySearch(s1, "Tom"));
System.out.println("s1:" + Arrays.toString(s1));
}
public void testIntArray() {
int[] a1 = new int[5], a2 = new int[5], a3 = { 4, 5, 6, 3, 9, 4 };
Arrays.fill(a1, 100);
System.arraycopy(a1, 0, a2, 0, a1.length);
System.out.println("a1是否和a2相等:" + Arrays.equals(a1, a2));
Arrays.sort(a3);
System.out.println("5在a3中的位置:" + Arrays.binarySearch(a3, 5));
System.out.println(Arrays.toString(a3));
}
public static void main(String[] args) {
ArraysTester arraystest = new ArraysTester();
arraystest.testStringArray();
arraystest.testIntArray();
}
}
输出结果:
s1是否等于s2:true
排序后的s1是否等于s2:false
Tom在s1中的位置:3
s1:[Jack, Marry, Mike, Tom, Tom2]
a1是否和a2相等:true
5在a3中的位置:3
[3, 4, 4, 5, 6, 9]