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 }
  • 相关阅读:
    orbis 链接 .a的问题
    程序的循环结构
    程序分支控制
    字符类型及常用的函数
    数字数据类型
    基础练习
    了解计算机
    python基础练习
    markdown基本使用
    jupyterhub
  • 原文地址:https://www.cnblogs.com/program-ccc/p/5324415.html
Copyright © 2011-2022 走看看