关于插入排序,希尔排序,堆排序的java实现
//插入排序
public static void insertionSort(int[] ints){
int i, j;
for(i = 1; i < ints.length; i++){
int temp = ints[i];
for(j = i; (j > 0) && (temp < ints[j-1]); j--){ //顺序
ints[j] = ints[j-1];
}
ints[j] = temp;
}
}
//希尔排序
//采用希尔增量
public static void sellSort(int[] ints) {
for(int step = ints.length/2; step > 1; step /= 2){
for(int i = step; i <ints.length; i += step){
int temp = ints[i];
int j;
for( j = i; j >= step && temp < ints[j-step]; j-=step){
ints[ j ]=ints[j-step];
}
ints[j] = temp;
}
}
}
//采用Hibbard增量
public static void sellSort_hb(int[] ints) {
for(int step = ints.length-1; step > 1; step = (step+1)/2-1){
for(int i = step; i <ints.length; i += step){
int temp = ints[i];
int j;
for( j = i; j >= step && temp < ints[j-step]; j-=step){
ints[ j ]=ints[j-step];
}
ints[j] = temp;
}
}
}
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
// 堆排序-2
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
//获取leftchile
static int getLetf(int index) {
return 2*index+1;
}
//排序
static void heapSort2(int[] ints){
//建堆
for(int i = ints.length/2 - 1; i >= 0; i--)
heapAdjust(ints, i, ints.length);
//取出堆顶元素
for(int j = ints.length-1; j > 0; j--){
//将堆顶元素和最后一个元素换位置
swap(ints,j,0);
//交换值后调整堆中元素位置
heapAdjust(ints, 0, j);
}
}
/**
* 交换元素
* @param arr
* @param a 元素的下标
* @param b 元素的下标
*/
static void swap(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
/**
* 调整
* @param ints 待调整堆
* @param nodeIndex 处理节点下标
* @param length 待处理堆长度,
* 因为排序后堆容量变小,排序后元素存储在该数组尾部,所以要用length标记要调整的堆的有效长度
*/
static void heapAdjust(int[] ints, int nodeIndex, int length){
int childIndex;
int node;
for(node = ints[nodeIndex]; getLetf(nodeIndex) < length; nodeIndex = childIndex){
childIndex = getLetf(nodeIndex);
if(childIndex < length && ints[childIndex+1] > ints[childIndex]){ //指向较大的孩子
childIndex++;
}
if(node < ints[childIndex]) //指向较大的孩子
ints[nodeIndex] = ints[childIndex];
else
break; //跳出
}
ints[nodeIndex] = node;
}