public class Sort{
public void swap(int[] array, int i, int j){ //简单的本地交换函数;
int temp = array[i] ;
array[i] = array[j] ;
array[j] = temp ;
}
public void bubbleSort(int[] array){ //冒泡排序;
int len = array.length ;
for(int i=1;i<len;i++){
for(int j=0;j<len-i;j++){
if(array[j]>array[j+1]){
swap(array,j,j+1) ;
}
}
}
}
public void insertSort(int[] array){ // 插入排序;
int len = array.length ;
for(int i=1;i<len;i++){
for(int j=i;j>0;j--){
if(array[j]<array[j-1]){
swap(array,j,j-1) ;
}
}
}
}
public void chooseSort(int[] array){ //选择排序;
int len = array.length ;
for(int i=0;i<len-1;i++){
int min = i ;
for(int j=i+1;j<len;j++){
if(array[min]>array[j]){
min = j ;
}
swap(array,min,i) ;
}
}
}
public void quickSort(int[] array){ //快速排序;
QSort(array,0,array.length-1) ;
}
public void QSort(int[] array, int left, int right){
if(left<=right){
int i = left ;
int j = right ;
int temp = array[left] ;
while(i!=j){
while(j>i && array[j]>=temp){
j-- ;
}
while(j>i && array[i]<=temp){
i++ ;
}
if(i<j){
swap(array,i,j) ;
}else{
swap(array,i,left) ;
QSort(array,left,i-1) ;
QSort(array,i+1,right) ;
}
}
}
}
int[] tempArray ;
public void mergeSort(int[] array){ //归并排序;
tempArray = new int[array.length] ;
MSort(array,0,array.length-1) ;
}
public void MSort(int[] array, int left, int right){
if(left<right){
int center = (left + right)/2 ;
MSort(array,left,center) ;
MSort(array,center+1,right) ;
Merge(array,left,center+1,right) ;
}else{
return ;
}
}
public void Merge(int[] array,int lpos,int rpos, int rightEnd){
int leftEnd = rpos - 1 ;
int i = lpos ;
int j = rpos ;
int k = lpos ;
while(i<=leftEnd && j<=rightEnd){
if(array[i]<=array[j]){
tempArray[k] = array[i] ;
i++ ;
k++ ;
}else{
tempArray[k] = array[j] ;
k++ ;
j++ ;
}
}
while(i<=leftEnd){
tempArray[k] = array[i] ;
k++ ;
i++ ;
}
while(j<=rightEnd){
tempArray[k] = array[j] ;
k++ ;
j++ ;
}
int len = rightEnd - lpos + 1 ;
for(int l=0;l<len;l++){
array[rightEnd] = tempArray[rightEnd] ;
rightEnd-- ;
}
}
public static void main(String[] args){ //测试;
Sort s = new Sort() ;
int[] array = {9,8,7,6,5,4,3,2,1} ;
//s.bubbleSort(array) ;
//s.quickSort(array) ;
s.mergeSort(array) ;
//s.insertSort(array) ;
//s.chooseSort(array) ;
for(int i=0;i<array.length;i++){
System.out.print(array[i] + " ") ;
}
}
}