zoukankan      html  css  js  c++  java
  • 排序之归并排序

    一、思想:分治策略,将问题分成一些小的问题然后递归求解,先划分至元素区间大小为1,后合并,在合并过程中有序

    二、时间复杂度:

    最坏:O(nlogn)

    最好:O(nlogn)

    平均:O(nlogn)

    三、辅助空间:O(N),主要用于合并

    四、稳定性:稳定

    五、适用场合:n较大时

     1 import java.util.Arrays;
     2 import java.util.Scanner;
     3 //最好,最坏,平均,均为O(nlogn),稳定,辅助空间O(n)(将两边进行合并时用)
     4 public class MergeSort {
     5     public static void merge(int[] a,int low,int mid,int high) {
     6         int[] temp = new int[high-low+1];//辅助空间O(n)
     7         int t=0;
     8         int i = low;//右指针
     9         int j = mid+1;//左指针
    10         while(i <= mid && j <= high) {//控制越界
    11             if(a[i]<=a[j])//=保证算法稳定性
    12             {
    13                 temp[t++] = a[i++];
    14             }
    15             else
    16             {
    17                 temp[t++] = a[j++];
    18             }
    19         }
    20         while(i<=mid) {//将左边剩余的数放入
    21             temp[t++] = a[i++];
    22         }
    23         while(j<=high) {//将右左边剩余的数放入
    24             temp[t++] = a[j++];
    25         }
    26         for(int k = 0; k < temp.length; k++) {
    27             a[low+k] = temp[k];//注意数组起始位置low+k
    28         }
    29     }
    30     public static void mergeSort(int[] a,int low,int high) {
    31         int mid = (low+high)/2;
    32         if(low<high) {
    33             mergeSort(a,low,mid);//左边
    34             mergeSort(a,mid+1,high);//右边
    35             merge(a,low,mid,high);//左右归并
    36             //System.out.println(Arrays.toString(a));
    37         }
    38         
    39     }
    40     public static void main(String[] args) {
    41         Scanner cin = new Scanner(System.in);
    42         int array[]= new int[5],i=0;
    43         while(i<array.length)
    44         {
    45             array[i] = cin.nextInt();
    46             i++;
    47         }
    48         i=0;
    49         mergeSort(array,0,array.length - 1);
    50         while(i<array.length) {
    51             System.out.print(array[i]+",");
    52             i++;
    53         }
    54     }
    55 
    56 }
  • 相关阅读:
    apache的httpclient进行http的交互处理
    Java 基础篇之反射
    死磕 java线程系列之创建线程的8种方式
    Spring Boot(三) 使用Lombok
    Spring Boot (七): Mybatis极简配置
    Spring Boot Thymeleaf 实现国际化
    微项目:一步一步带你使用SpringBoot入门(二)
    SSM框架手动实现分页逻辑(非PageHelper)
    Java 基础篇之集合
    一起来学Java注解(Annotation)
  • 原文地址:https://www.cnblogs.com/lizijiangmm/p/8644796.html
Copyright © 2011-2022 走看看