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 }
  • 相关阅读:
    设备驱动开发之缓冲区读写操作
    什么是80Plus
    INF Manufacturer Section
    C++编程获得某台机器的IP地址
    INF DestinationDirs Section
    importlib模块
    django的内置信号
    auth模块(登录验证)
    头像文件的预览
    powerDesiger 常用设置
  • 原文地址:https://www.cnblogs.com/lizijiangmm/p/8644796.html
Copyright © 2011-2022 走看看