工具类---数组操作ArrayUtil(二)
- 1);
}
/**
* 快速排序的具体实现,排正序
*
* @since 1.1
* @param source
* 需要进行排序操作的数组
* @param low
* 开始低位
* @param high
* 结束高位
* @return 排序后的数组
*/
private static int[] qsort(int source[], int low, int high) {
int i, j, x;
if (low < high) {
i = low;
j = high;
x = source[i];
while (i < j) {
while (i < j && source[j] > x) {
j--;
}
if (i < j) {
source[i] = source[j];
i++;
}
while (i < j && source[i] < x) {
i++;
}
if (i < j) {
source[j] = source[i];
j--;
}
}
source[i] = x;
qsort(source, low, i - 1);
qsort(source, i + 1, high);
}
return source;
}
///////////////////////////////////////////////
//排序算法结束
//////////////////////////////////////////////
/**
* 二分法查找 查找线性表必须是有序列表
*
* @since 1.1
* @param source
* 需要进行查找操作的数组
* @param key
* 需要查找的值
* @return 需要查找的值在数组中的位置,若未查到则返回-1
*/
public static int binarySearch(int[] source, int key) {
int low = 0, high = source.length - 1, mid;
while (low <= high) {
mid = (low + high) >>> 1;
if (key == source[mid]) {
return mid;
} else if (key < source[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
/**
* 反转数组
*
* @since 1.1
* @param source
* 需要进行反转操作的数组
* @return 反转后的数组
*/
public static int[] reverse(int[] source) {
int length = source.length;
int temp = 0;
for (int i = 0; i < length>>1; i++) {
temp = source[i];
source[i] = source[length - 1 - i];
source[length - 1 - i] = temp;
}
return source;
}
/**
* 在当前位置插入一个元素,数组中原有元素向后移动;
* 如果插入位置超出原数组,则抛IllegalArgumentException异常
* @param array
* @param index
* @param insertNumber
* @return
*/
public static int[] insert(int[] array, int index, int insertNumber) {
if (array == null || array.length == 0) {
throw new IllegalArgumentException();
}
if (index-1 > array.length || index <= 0) {
throw new IllegalArgumentException();
}
int[] dest=new int[array.length+1];
System.arraycopy(array, 0, dest, 0, index-1);
dest[index-1]=insertNumber;
System.arraycopy(array, index-1, dest, index, dest.length-index);
return dest;
}
/**
* 整形数组中特定位置删除掉一个元素,数组中原有元素向前移动;
* 如果插入位置超出原数组,则抛IllegalArgumentException异常
* @param array
* @param index
* @return
*/
public static int[] remove(int[] array, int index) {
if (array == null || array.length == 0) {
throw new IllegalArgumentException();
}
if (index > array.length || index <= 0) {
throw new IllegalArgumentException();
}
int[] dest=new int[array.length-1];
System.arraycopy(array, 0, dest, 0, index-1);
System.arraycopy(array, index, dest, index-1, array.length-index);
return dest;
}