【Java】五种常见排序之----------------归并排序

来源:互联网 发布:淘宝首页没有高级搜索 编辑:程序博客网 时间:2024/05/29 14:57
          • 原理:将两个或两个以上的有序表,合并成一个新的有序表的过程
          • 时间复杂度:O(nlogn)
          • 空间复杂度:归并排序算法稳定,数组需要O(n)的额外空间,链表需要O(log(n))的额外空间
          • 原理及代码:
package paixu;
/**
 * @author xpengfei
 */
import java.util.Scanner;


/*
 * 归并排序(采用的是分治法)
 * 简介:将两个(或两个以上)有序表合并成一个新的有序表 即把待排序序列分为若干个子序列,
 * 每个子序列是有序的。然后再把有序子序列合并为整体有序序列 
 * 时间复杂度为O(nlogn)
 * 归并排序算法稳定,数组需要O(n)的额外空间,链表需要O(log(n))的额外空间
 */
public class sortFour {
Scanner input=new Scanner(System.in);
private static int n;
private static int num[];
public sortFour(){
System.out.println("请输入数组规模大小:");
n=input.nextInt();
num=new int[n];
System.out.println("随机生成的数组如下:");
for(int i=0;i<n;i++){
num[i]=(int)(Math.random()*1000);
System.out.println(num[i]);
}
}
public void SortFour(int []nums,int low,int high){
int mid=(low+high)/2;
if(low<high){
SortFour(nums, low, mid);//左边
SortFour(nums, mid+1, high); //右边
merge(nums, low, mid, high);
}
}
public static void merge(int[]nums,int low,int mid,int high){
int []temp=new int[high-low+1];
int left=low;//左指针
int right=mid+1;//右指针
int k=0;
//把较小的数先移到新数组中
while(left<=mid && right<=high){
if(nums[left]<nums[right]){
temp[k]=nums[left];
}else{
temp[k]=nums[right];
}
}
//把左边剩余的数移入数组
while(left<=mid){
temp[k]=nums[left];
}
//把右边剩余的数移入数组
while(right<=high){
temp[k]=nums[right];
}
//把新数组中的数覆盖旧数组
for(int flag=0;flag<temp.length;flag++){
nums[flag]=temp[flag];
}
}
public void display(){
System.out.println("排序后的数组如下:");
for(int i=0;i<n;i++){
System.out.println(num[i]);
}
}
public static void main(String[] args) {
sortFour Sfour=new sortFour();
Sfour.SortFour(num, 0, n-1);
Sfour.display();
}
}

0 0
原创粉丝点击