快排
class QuikSort {
public void sort ( int [ ] array) {
int len = array. length;
if ( len < 1 )
return ;
quikSort ( array, 0 , len - 1 ) ;
}
private void quikSort ( int [ ] array, int left, int right) {
if ( left > right)
return ;
int i = left;
int j = right;
int pivot = array[ left] ;
while ( i < j) {
while ( i < j && array[ j] >= pivot) {
j-- ;
}
while ( i < j && array[ i] <= pivot) {
i++ ;
}
if ( i < j ) {
int temp = array[ i] ;
array[ i] = array[ j] ;
array[ j] = temp;
}
}
array[ left] = array[ i] ;
array[ i] = pivot;
quikcSort ( array, 0 , i - 1 ) ;
quikcSort ( array, i + 1 , right) ;
}
}
归并
public class mergeSort {
public int [ ] copyOfRange ( int [ ] array, int left, int right) {
int len = right - left;
int [ ] newArray = new int [ len] ;
int j = 0 ;
for ( int i = left; i < right; i++ ) {
newArray[ j] = array[ i] ;
j++ ;
}
return newArray;
}
public int [ ] mergeSort ( int [ ] array) {
int len = array. length;
if ( len < 2 )
return array;
int midIndex = len / 2 ;
int [ ] left = copyOfRange ( array, 0 , midIndex) ;
int [ ] right = copyOfRange ( array, midIndex, len) ;
return merge ( mergeSort ( left) , mergeSort ( right) ) ;
}
public int [ ] merge ( int [ ] a1, int [ ] a2) {
int [ ] a3 = new int [ a1. length + a2. length] ;
int i = 0 ;
int j = 0 ;
int index = 0 ;
while ( i < a1. length && j < a2. length) {
if ( a1[ i] > a2[ j] ) {
a3[ index] = a2[ j] ;
index++ ;
j++ ;
} else {
a3[ index] = a1[ i] ;
index++ ;
i++ ;
}
}
while ( i < a1. length) {
a3[ index] = a1[ i] ;
index++ ;
i++ ;
}
while ( j < a2. length) {
a3[ index] = a2[ j] ;
index++ ;
j++ ;
}
return a3;
}
}
希尔排序
public class ShellSort {
public static int [ ] shellSort ( int [ ] array) {
int len = array. length;
if ( len < 2 ) {
return array;
}
int gap = len / 2 ;
while ( gap > 0 ) {
for ( int i = gap; i < len; i++ ) {
for ( int j = i; j >= 0 ; j -= gap) {
int preIndex = j - gap;
if ( preIndex >= 0 && array[ preIndex] > array[ j] ) {
int temp = array[ preIndex] ;
array[ preIndex] = array[ j] ;
array[ j] = temp;
}
}
}
gap /= 2 ;
}
return array;
}
}