冒泡
public static void bubble(int []array ){
for (int i=0 ; i<array .length-1 ; i++){
for (int j=i+1 ; j<array .length; j++){
if (array [i] > array [j]){
int tmp;
tmp = array [j];
array [j] = array [i];
array [i] = tmp;
}
}
}
}
插入
public static void insert(int []array ){
int i,j;
int currentValue;
int position;
for (i=1 ;i<array .length;i++)
{
currentValue = array [i];
position = i;
for (j=i-1 ;j>=0 ;j--){
if (array [j]>currentValue){
array [j+1 ]=array [j];
position--;
}else {
break ;
}
}
array [position] = currentValue;
}
}
快速
public static void quickSort(int [] array ){
if (array .length>0 )
quick(array ,0 ,array .length-1 );
}
public static void quick(int [] array , int low, int high){
if (low < high){
int middle = getMiddle(array ,low,high);
quick(array ,low,middle-1 );
quick(array ,middle+1 ,high);
}
}
public static int getMiddle(int [] array , int low, int high){
int tmp = array [low];
while (low < high){
while (low<high && array [high]>=tmp){
high--;
}
array [low] = array [high];
while (low<high && array [low]<=tmp){
low++;
}
array [high] = array [low];
}
array [low] = tmp;
return low;
}
归并
public static void mergeSort(int [] array , int low,int high){
int middle = (low+high)/2 ;
if (low < high){
mergeSort(array ,low,middle);
mergeSort(array ,middle+1 ,high);
merge(array ,low,middle,high);
}
}
public static void merge(int [] array , int low,int midle, int high){
int [] tmp = new int [high+1 -low];
int middle = (low+high)/2 ;
int i = low;
int j = middle + 1 ;
int k = 0 ;
while (i<=middle&&j<=high){
if (array [i]<array [j]){
tmp[k++] = array [i++];
}else {
tmp[k++] = array [j++];
}
}
if (i<=middle){
System.arraycopy(array , i, tmp, k, middle+1 -i);
}
if (j<=high){
System.arraycopy(array , j, tmp, k+middle+1 -i, high+1 -j);
}
System.arraycopy(tmp, 0 , array , low, tmp.length);
}