java实现排序算法
package wh1005;
public class Sort {
public void swap(int[] array,int i,int j){
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public int[] BubbleSort(int[] array){
for (int i = 0; i < array.length; i++) {
for (int j = i+1; j <array.length-i-1 ; j++) {
if(array[j]>array[j+1]){
swap(array,j,j+1);
}
}
}
return array;
}
public int[] BetterBubble(int[] array){
for (int i = 0; i < array.length; i++) {
boolean flag = true;
for(int j= i;j<array.length-1-i;j++){
if(array[j]>array[j+1]){
flag = false;
swap(array,j,j+1);
}
if(flag == true){
break;
}
}
}
return array;
}
public int[] SelectSort(int[] array){
for (int i = 0; i < array.length; i++){
int index = i;
for(int j = i;j<array.length;j++){
if(array[j]>array[index]){
index = j;
}
}
if(i!=index){
swap(array,i,index);
}
}
return array;
}
public int[] InsertSort(int[] array){
for (int i = 1; i < array.length; i++) {
for(int j=i;j>0;j--){
if(array[j]>array[j-1]){
swap(array,j,j-1);
}
}
}
return array;
}
public int[] ShellSort(int[] array){
int h = 1;
while (h<array.length/2){
h = 2*h+1;
}
while (h>=1){
for (int i = h; i <array.length ; i++) {
for(int j = i;j>=h;j-=h){
if(array[j]>array[j-h]){
swap(array,j,j-h);
}else{
break;
}
}
}
h = h/2;
}
return array;
}
public void Sort(int[] array,int left,int right){
if(left >= right){
return;
}
int mid = left + (right-left)/2;
Sort(array,left,mid);
Sort(array,mid+1,right);
merge(array, left,mid,right);
}
private void merge(int[] array, int left, int mid, int right) {
int[] temp = new int[right-left+1];
int k = 0;
int l = left;
int r = mid+1;
while(left<mid && r<right){
if(array[l]>array[r]){
temp[k++] = array[l++];
}else{
temp[k++] = array[r++];
}
}
while (l<mid){
temp[k++] = array[l++];
}
while (r<right){
temp[k++] = array[r++];
}
for(int z = 0;z<temp.length;z++) array[left+z] = temp[z];
}
public void QuickSort(int[] array,int left,int right){
int i = left;
int j = right;
int base = array[left];
while(i!=j){
while (array[j]>=base && i<j){
j--;
}
while (array[i]<=base && i<j){
i++;
}
swap(array,i,j);
}
swap(array,i,left);
QuickSort(array,left,j-1);
QuickSort(array,j+1,right);
}
}