您的位置:首页 > 其它

经典排序算法(希尔排序,归并排序,快速排序,插入排序)

2014-09-10 11:08 253 查看
public static void main(String[] args){
int[]a={13,50,6,9,8,7,12,15,100,4};
//insertSort(a);
//shellSort(a);
//quickSort1(a,0,a.length-1);
int []temp=new int[a.length];
mergeSort(a,0,a.length-1,temp);
for(int cc:a)
{
System.out.print(cc+"  ");
}
}
public static void insertSort(int[] a){
int key=0;
int i=0;
for(int j=2;j<a.length;j++){
key=a[j];
i=j-1;
while(i>=0&&a[i]>key){
a[i+1]=a[i];
i--;
}
a[i+1]=key;
}
}
public static void shellSort(int[] a){
int size=a.length;
for(int gap=size/2;gap>=1;gap/=2){
for(int i=gap;i<size;i++){
int temp=a[i];
int k;
for(k=i-gap;k>=0&&a[k]>temp;k-=gap){
a[k+gap]=a[k];
}
a[k+gap]=temp;
}
}
}
public static void quickSort1(int[] a,int L,int R){
if(L<R){
int i=L,j=R,key=a[L];
while(i<j){
while(i<j&&a[j]>=key){
j--;
}
if(i<j){
a[i++]=a[j];
}
while(i<j&&a[i]<key){
i++;
}
if(i<j){
a[j--]=a[i];
}
}
a[i]=key;
quickSort1(a,L,i-1);
quickSort1(a,i+1,R);
}
}
//合并数组
public static void mergeSort(int a[],int first,int mid,int end,int[] temp){
int i=first,j=mid+1;
int m=mid,n=end;
int k=0;
while(i<=m&&j<=n){
if(a[i]<=a[j]){
temp[k++]=a[i++];
}else{
temp[k++]=a[j++];
//count+=m-i+1;          还可以统计逆序对,n*lgn时间复杂度
}
}
while(i<=m){
temp[k++]=a[i++];
}
while(j<=n){
temp[k++]=a[j++];
}
for(i=0;i<k;i++){
a[first+i]=temp[i];
}
}
public static void mergeSort(int[] a,int first,int last,int[] temp){
if(first<last){
int mid=(first+last)/2;
mergeSort(a,first,mid,temp);
mergeSort(a,mid+1,last,temp);
mergeSort(a,first,mid,last,temp);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐