//希尔排序
public void shellSort(int increment){
int inner,outer;
long temp;
int h = 1; // find initial value of h
while(h <= nElems/increment) h = h*increment+1;
while(h>0){ //decreasing h ,until h = 1
for(outer = h;outer < nElems;outer++){
temp = a[outer];
inner = outer; // one subpass(eg 0,4,8)
while(inner > h-1&&a[inner-h] >= temp){
a[inner] = a[inner-h];
inner -= h;
}//end for
a[inner] = temp;
}//end while(h>0)
h = (h-1)/increment; //decrease
}//end shellSort()
}
//划分
public int partitionIt(int left,int right,int pivot){
int leftPtr = left-1; // right of first elem
int rightPtr = right+1; //left of pivot
public void swap(int dex1, int dex2) // swap two elements
{
long temp = a[dex1]; // A into temp
a[dex1] = a[dex2]; // B into A
a[dex2] = temp; // temp into B
} // end swap
//快速排序1(递归实现)
public void recQuickSort(int left,int right){
if(right<=left){ // if size is 1,it's already sorted
return;
}else{ //size is 2 or larger
int pivot = right;
int partition = this.partitionIt(left, right, pivot);
recQuickSort(left,partition-1); //sort left
recQuickSort(partition,right);//sort right
}
}
//快速排序2(对于中枢pivot的选取采用三数据取中值的方法)
public void recQuickSort2(int left,int right){
int size = right-left+1;
if(size<=3){
manualSort(left,right);
}else{ //数组长度大于3使用快速排序
int median = medianOf3(left,right);
int partition = partitionIt(left, right, median);
recQuickSort2(left,partition-1); //sort left
recQuickSort2(partition,right);//sort right
}
}//end recQuickSort2
private int medianOf3(int left, int right) {// return pivot
int center = (left+right)/2;
if(a[left] > a[center]){
swap(left,center);
}
if(a[left]> a[right]){
swap(left,right);
}
if(a[center] > a[right]){
swap(center,right);
}
swap(center,right-1);
return right-1;
}
private void manualSort(int left,int right){
int size = right-left+1;
if(size==1)return; //no sort necessary
if(size==2){
if(a[left]>a[right]){
swap(left,right);
}
return;
}
if(a[left]>a[left+1]){
swap(left,left+1);
}
if(a[left]>a[right]){
swap(left,right);
}
if(a[left+1]>a[right]){
swap(left+1,right);
}
}//end manualSort