选择排序
import java.Util.*;
public class SelectionSort(){
private SectionSort(){}
public static void sort(Comparable[] arr){
int n=arr.length;
for(int i=0;i<n;i++){
int minIndex=i;
for(int j=i+1;j<n;j++)
if(arr[j].comparaTo(arr.[minIndex])<0)
minIndex=j;
swap(arr,i,minIndex);
}
}
private static void swap(Object[] arr,int i,int j){
Object t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
插入排序
import java.Util.*;
public class InsertionSort{
public InsertionSort(){}
public static void sort(Comparable[] arr){
int n=arr.length;
for(int i=0;i<n;i++)
Comparable e=arr[i];
int j=i;
for(;j>0&&arr[j-1].comparaTo(e)>0,j--)
arr[j]=arr[j-1];
arr[j]=e;
}
}
private static void swap(Object[] arr,int i,int j){
Object t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
冒泡排序
public class BubbleSort{
private BubbleSort(){}
public static void sort(Comparable[] arr){
int n= arr.length;
boolean swapped=false;
do{
swapped=false;
for(int i=1;i<n,i++)
if(arr[i-1].comparaTo(arr[i])>0)
swap(arr,i-1,i);
swapped=true;
}
n--;
}while(swapped);
}
private static void main(Object[] arr,int i, int j){
Object t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
希尔排序
public class ShellSort{
private ShellSort(){
public static void sort(Comparable[] arr){
int n=arr.length;
int h=1;
while(h<n/3)
h=3*h+1;
while(h>=1){
for(int i=h;i<n;i++){
aomparable e=arr[i];
int j=i;
for(;j>=h&&e.comparaTo(arr[j-h])<0;j-=h)
arr[j]=arr[j-h];
arr[j]=e;
}
h/=3;
}
}
}
归并排序
import java.util.*
public class MergeSort{
private MergeSort(){
private MergeSort(){}
private static void merge(Comparabe[] arr,int l,int mid, int r){
Comparable[] aux=Arrays.copyOfRange(arr,l,r+1);
int i=l,j=mid+1;
for(int k=l;k<=r;k+)
if(i>mid){
arr[k]=aux[j-1];
j++;
}
else if(j>r){
arr[k]=aux[i-1];
i++;
}
else if(aux[i-1].comparaTo(aux[j-1])<0){
arr[k]=aux[i-1];
i++;
}
else{
arr[k]=aux[j-1];
j++;
}
}
}
快速排序
import java util.*
public class QuickSort{
private QuickSort(){}
private static void partition(Comparable[] arr,int l; int r){
swap(arr,l,(int)Math.random()*(r-l+1)+1);
Comparable v=arr[l];
int j=l;
for(int i=l+1,i<=r,i++)
if(arr[i].comparaTo(v)<0){
j++;
swap(arr,j,i);
}
swap(arr,l,j);
return j;
}
private static void sort(Comparable[] arr,int l,int r){
if(r-l<15){
InsertionSort.sort(arr,l,r);
sort(arr,l,p-1);
sort(arr,p+1,r);
}
public static void sort(Comparable[] arr){
int n=arr.length;
sort(arr,0,n-1);
}
private static void swap(Object[] arr,int i, int j){
Object t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}