zoukankan      html  css  js  c++  java
  • 第七章 快速排序

    package chap07_Quick_Sort;
    
    import static org.junit.Assert.*;
    
    import java.util.Arrays;
    
    import org.junit.Test;
    
    public class SortAlgorithms {
        /**
         * 快速排序算法
         * 
         * @param n
         */
        static void quickSort(int[] n) {
            int from = 0;
            int to = n.length;
            // quickSort(n, from, to);
            quickSort1(n, from, to);
    
        }
    
        /**
         * 快速排序的递归实现,将n从start到end之间的数字排序(不包括end)
         * 
         * @param n
         * @param start
         * @param end
         */
        static protected void quickSort(int[] n, int start, int end) {
            if (start < end - 1) {
                int a;
                a = partition(n, start, end);
    
                quickSort(n, start, a);
                quickSort(n, a, end);
            }
        }
    
        /**
         * 快速排序的迭代实现
         * 
         * @param n
         * @param start
         * @param end
         */
        static protected void quickSort1(int[] n, int start, int end) {
            int a = partition(n, start, end);
            int b = a;
            while (start < a - 1) {
                a = partition(n, start, a);
            }
            while (b < end - 1) {
                b = partition(n, b, end);
            }
        }
    
        /**
         * 分割(快速排序中对数组的分割)
         * 
         * @param n
         * @param start
         * @param end
         * @return
         */
        protected static int partition(int[] n, int start, int end) {
            int p = end - 1;
            int s = start;// s位于大于a[p]和小于a[p]之间的位置
            int tmp;
            for (int i = start; i < end; i++) {
                if (n[i] < n[p]) {
                    tmp = n[i];
                    n[i] = n[s];
                    n[s] = tmp;
                    s++;
                }
            }
            {
                tmp = n[s];
                n[s] = n[p];
                n[p] = tmp;
            }
            return s;
        }
    
        @Test
        public void testName() throws Exception {
            int[] a = { 13, 19, 9, 5, 12, 8, 7, 4, 21, 2, 6, 11 };
            // System.out.println(Arrays.toString(a));
            // partition(a, 0, 12);
            quickSort(a);
            System.out.println(Arrays.toString(a));
        }
    }
  • 相关阅读:
    单例模式和配置admin
    ORM单表查询,跨表查询,分组查询
    进程同步控制 Lock Semaphore Event
    创建进程和多进程 process join p.daemon terminate
    并发编程基础
    远程执行模块和黏包 socketserve hamc模块验证合法性
    网络编程之Socket
    网络基础
    del new item hash 单例模式
    面向对象进阶
  • 原文地址:https://www.cnblogs.com/xiaojintao/p/3780584.html
Copyright © 2011-2022 走看看