归并排序 && 快速排序 ——分治思想

对数组进行归并排序:——分治法

分治法思想:先将原问题,分解成几个可独立求解的子问题, 等子问题求解后, 用适当方法,将子问题的解合并成原问题的解;

通常,由于子问题与原问题有相同的类型,故可使用递归实现。

数组的归并排序:

实现:

package com.algothrim;


/*
* 归并排序的实现
*/
public class DivideAndConquer {
  public void mergeSort(int[] A,int low,int high){
    if(low<high){
      int mid=(low+high)/2;
      mergeSort(A,low,mid);
      mergeSort(A,mid+1,high);
      merge(A,low,mid,high);
    }
  }
public void merge(int[] A,int low,int mid,int high){
    int[] B=new int[high-low+1]; //辅助数组
    int p1=low;
    int p2=mid+1;
    int p3=0;
    for(;p1<=mid && p2<=high;){
      if(A[p2]<A[p1]) //哪个小就复制哪个——从小到大排序;
        B[p3++]=A[p2++];
      else
      B[p3++]=A[p1++];
    }
    while(p1<=mid)
      B[p3++]=A[p1++];
    while(p2<=high)
      B[p3++]=A[p2++];
  //复制回原来数组
    for(int i=low,j=0;i<=high && j<B.length;i++,j++)
    A[i]=B[j];

}
public static void main(String[] args) {
  DivideAndConquer divider=new DivideAndConquer();
  int A[]={33,12,5,2,3,7,25,18,42,15,90};
  System.out.print("排序前:");
  for(int i=0;i<A.length;i++)
  System.out.print(" "+A[i]);
  System.out.println();

DivideAndConquer divider=new DivideAndConquer();  

  //使用归并排序
    // divider.mergeSort(A, 0, A.length-1);


    //使用快速排序
    divider.quickSort(A, 0, A.length-1);

  System.out.print("排序后:");
  for(int i=0;i<A.length;i++)
  System.out.print(" "+A[i]);

}

//快速排序
public void quickSort(int[] a,int low,int high){
  if(high<=low) return;
  int j=partition(a,low,high);
  quickSort(a,low,j-1);
  quickSort(a,j+1,high);
  }
public int partition(int[] a,int low,int high){
  int base=a[low];
  int i,j;
  for(i=low,j=high+1;;){ //之所以初始化为low,high+1,是因为i,j将要作前自增,前自减操作。
    while(a[++i]<base) //之前使用i++导致,i指向了欲交换元素的下一个位置。
      if(i==high) break;
    while(a[--j]>base)
      if(j==low)  break;
    if(i>=j) break;
  exch(a,i,j);
  }
  exch(a,j,low);
  return j;
  }
  public void exch(int[] a,int i,int j){
    int temp=a[i];
    a[i]=a[j];
    a[j]=temp;
  }}

 

 

归并排序:

    先对两个子集合操作(递归本函数),再整体排序(归并排序)。

快速排序:

    先整体划分成两个子集合(划分排序),再对两个子集合操作(递归本函数)。

 


 

分治法:当输入规模n相当大时,直接求解困难,应该分析问题本身特性,再根据这些特性选择适当的策略。

  将这n个输入分成k个不同子集合,若能得到这k个不同的可独立求解的子问题:1<=k<=n,且在求出子问题的解后,再用适当方法合并成整个问题的解:

整个问题分成若干子问题,分而治之。

1.  二分检索法

题1:求最大,最小元素

2. 归并分类

归并排序

3.快速分类

快速排序

4.选择问题

寻找第k小元素

5 斯特拉森矩阵

 将矩阵分块计算

转载于:https://www.cnblogs.com/dan-cnblogs/p/4732590.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值