算法-归并排序演示

归并排序

排序原理:
1、尽可能的一组数据拆分成两个元素相等的子组,并对每一个子组继续拆分,直到拆分后的每个子组的元素个数是1为止。
2、将相邻的两个子组进行合并成一个有序的大组;
3、不断的重复步骤2,直到最终只有一个组为止。
在这里插入图片描述

源码

 public class Merge
    {
        private static int[] result;


        public static List<int[]> res=new List<int[]>();

        public static void sort(int[] a)
        {
            result=new int[a.Length];
            res.Clear();
            res.Add((int[])a.Clone());
            int low = 0;
            int high = a.Length - 1;
            sort(a,low,high);
        }

        /// <summary>
        /// 根据low到high之间的距离交换数组a的值
        /// </summary>
        /// <param name="a"></param>
        /// <param name="low"></param>
        /// <param name="high"></param>
        private static void sort(int[] a, int low, int high)
        {
            if (low >= high)
                return;
            int mid = low + (high - low) / 2;
            sort(a,low,mid);
            sort(a,mid+1,high);
            merge(a,low,mid,high);
        }

       /// <summary>
       /// 合并元素
       /// </summary>
       /// <param name="a"></param>
       /// <param name="low"></param>
       /// <param name="mid"></param>
       /// <param name="high"></param>
        private static void merge(int[] a, int low,int mid, int high)
       {
           int i = low;
           int p1 = low;
           int p2 = mid + 1;
           while (p1 <= mid && p2 <= high)
           {
               if (less(a[p1], a[p2]))
               {
                   result[i++] = a[p1++];
               }
               else
               {
                   result[i++] = a[p2++];
               }
           }

           while (p1 <= mid)
           {
               result[i++] = a[p1++];
           }

           while (p2 <= high)
           {
               result[i++] = a[p2++];
           }

           for (int index = low; index <= high; index++)
           {
               a[index] = result[index];
           }

           res.Add((int[])a.Clone());
       }

        /// <summary>
        /// 判断两个变量之间的大小
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        private static bool less(int a, int b)
        {
            return a.CompareTo(b) < 0;
        }

        /// <summary>
        /// 交换两个元素
        /// </summary>
        /// <param name="a"></param>
        /// <param name="i"></param>
        /// <param name="j"></param>
        private static void exch(int[] a, int i, int j)
        {
            int temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
    }

归并排序使用了递归来实现,比较难理解。
主要实现思想是分治思想。先分离 再合并。

演示

在这里插入图片描述
缺点:
需要申请额外的数组空间,导致空间复杂度提升,是典型的以空间换时间的操作。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
import java.awt.Color; import java.awt.Container; import java.awt.Font; import java.awt.Scrollbar; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Timer; import java.util.TimerTask; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.Scrollable; class SortWindow extends JFrame implements ActionListener //定义一个排序窗口类 { PaiXu px; //声明一个排序的对象 JButton start; //开始演示 JButton go; //继续演示 JButton suspend; //暂停 JButton end; //结束程序的播放,终止 JButton tuichu; //退出 Container con; JButton randomNumber; //用于产生待排序的随机数 int y[] = {0,0,0,0,0,0,0,0,0,0}; //用于按钮的初值 JButton[] x; JLabel title; //演示程序的标题 JButton button[]; JButton tempBtn[]; //按钮的中间变量,用于扭的设置 JTextArea mul; //用于算法演示 的说明信息 JTextArea ta; //显示动画排序的关键代码 JScrollPane sp; FileOutputStream fos ; FileInputStream fis; public SortWindow(String s) { px = new PaiXu(this); this.setTitle(s); x = new JButton[y.length]; Font f=new Font("新宋体",Font.BOLD,20); con = getContentPane(); con.setLayout(null); title = new JLabel("合并排序算法演示的课程设计。。。"); //title.setForeground(Color.red); title.setForeground(Color.blue); title.setFont(new Font("新宋体",Font.BOLD,40)); title.setBounds(70,100,600,40); //title.setBounds(30,50,600,40); con.add(title); mul = new JTextArea(); mul.setBounds(0, 470, 200,100); mul.setBackground(Color.gray); StringBuffer sb = new StringBuffer(); sb.append("注意:").append("\n"); sb.append("黑色表示生成的数").append("\n"); sb.append("红色表示两个数比较的位置").append("\n"); sb.append("绿色表示比比较的数小").append("\n"); sb.append("蓝色表示以排好了序的数").append("\n"); mul.setText(sb.toString()); mul.setForeground(Color.red); mul.setEditable(false); con.add(mul); ta = new JTextArea(); //shows用于显示关键的排序代码 ta.setVisible(true); ta.setEditable(false); //设置文本框为不可编辑 ta.setBackground(Color.yellow); //将ta的背景设置为黄色 sp = new JScrollPane(ta); sp.setLocation(690, 0); sp.setSize(350, 580); sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);//设置水平滚动条总是显示 sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); //设置垂直滚动条总是显示 con.add(sp); //shows.setFont(f); // shows.setBounds(700,130,400,360); // shows.setBounds(700,0,400,900); /////////////////////////////// // shows.setBounds(700,0,400,600); // shows.setCaretPosition(shows.getDocument().getLength()); // con.add(shows); randomNumber = new JButton("生成数"); randomNumber.setFont(f); // randomNumber.setBounds(50,400,110,30); randomNumber.setBounds(0,400,100,30); con.add(randomNumber); randomNumber.addActionListener(this); start = new JButton("开始"); start.setFont(f); // start.setBounds(200, 400, 80, 30); start.setBounds(120,400,80,30); con.add(start); start.addActionListener(this); /////////// go = new JButton("继续"); go.setFont(f); //go.setBounds(330,400,80,30); go.setBounds(220,400,80,30); con.add(go); go.addActionListener(this); //////// suspend = new JButton("暂停"); suspend.setFont(f); // suspend.setBounds(460,400,80,30); suspend.setBounds(320,400,80,30); con.add(suspend); suspend.addActionListener(this); end = new JButton("终止"); end.setFont(f); //end.setBounds(590, 400, 80, 30); end.setBounds(420,400,80,30); con.add(end); end.addActionListener(this); tuichu = new JButton("退出"); tuichu.setFont(f); //tuichu.setBounds(720,400,80,30); tuichu.setBounds(520,400,80,30); con.add(tuichu); tuichu.addActionListener(this); button = new JButton[y.length]; SortCode(); //显示动画排序的代码 for(int i = 0;i<y.length;i++) { button[i] = new JButton(String.valueOf(y[i])); button[i].setFont(f); button[i].setBounds(70 * i,200,60,30); con.add(button[i]); } for(int i = 0;i<y.length;i++) { x[i] = button[i]; } // this.setSize(700, 500); // this.setSize(900,500); //this.setSize(1100,500); this.setSize(1065,620); con.setBackground(Color.gray); //设置窗体的颜色 this.validate(); this.setVisible(true); // this.setResizable(false); this.setResizable(true); this.setDefaultCloseOperation(HIDE_ON_CLOSE); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getActionCommand().equals("生成数")) //如果响应的事件是生成数 { int num; for(int i=0;i < this.y.length;i++) //随机生成按钮上的数 { num = (int)(Math.random()*70); //得到随机数 this.button[i].setForeground(Color.black); this.button[i].setText(String.valueOf(num)); //将随机数赋值于的按钮 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值