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

    1.归并排序

    思路:采用分治思想将序列两两分组,然后再逐级将各组归并。详情见图:

    归并排序可求逆序对,详情见代码:

     1 import java.util.*;
     2 import static java.lang.System.*;
     3 
     4 public class Main{
     5     static Scanner in = new Scanner(System.in);
     6     
     7     static int sum;
     8     static void merge(int a[],int first,int mid,int last,int temp[])
     9     {
    10         int i=first,j=mid+1;
    11         int n=mid,m=last;
    12         int k=0;
    13         while(i<=n&&j<=m)
    14         {
    15             if(a[i]>a[j])
    16             {
    17                 temp[k++]=a[j++];
    18                 sum+=(j-first-k);//j-first表示该组中a[j]前面有几个数,k表示归并后a[j]在该组中的位置
    19             }
    20             else
    21                 temp[k++]=a[i++];
    22         }
    23         
    24         while(i<=n)    temp[k++]=a[i++];
    25         while(j<=m) temp[k++]=a[j++];
    26         for(int l=0;l<k;l++)
    27         {
    28             a[first+l]=temp[l];
    29         }    
    30     }
    31     static void MergeSort(int a[],int first,int last,int temp[])
    32     {
    33         if(first<last)
    34         {
    35             int mid=(first+last)/2;
    36             MergeSort(a,first,mid,temp);
    37             MergeSort(a,mid+1,last,temp);
    38             merge(a,first,mid,last,temp);
    39         }
    40     }
    41     
    42     public static void main(String[] args)
    43     {
    44         int a[] = {3,2,9,7,5,4};
    45         int temp[]=new int[20];
    46         MergeSort(a,0,a.length-1,temp);
    47         for(int elem:a)
    48             out.print(elem);
    49         out.println("
    序列的逆序数为:"+sum);
    50     }
    51 }
  • 相关阅读:
    bootstrap 模态框一闪而过的问题
    ${requestScope.paramName} 与 ${param.name}
    Android控件
    质量属性
    android基础知识复习一
    Numpy基础篇二
    miniconda 搭建tensorflow框架
    Numpy基础篇一
    pandas 数据索引与选取
    《架构漫谈》阅读笔记
  • 原文地址:https://www.cnblogs.com/program-ccc/p/5324415.html
Copyright © 2011-2022 走看看