zoukankan      html  css  js  c++  java
  • 排序算法-快速排序

    排序算法-快速排序

    今天所写的是排序算法中的快速排序,快速排序是JAVA排序中最常用的排序算法,

    主要是因为它的运行效率比较快,

    思路:以第一个数值作为key值,将所有比key值小的值放到key值得左边,比key值大的值放到key值右边
    通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一
    部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可
    递归进行,以此达到整个数据变成有序序列

    实现方法:

    package cn.zbvc.sorting;
    /**
    * 快速排序
    * @author Mr.guo
    *
    */
    public class FastDemo {
    
    public int[] fastDem(int[] a){
    
    int start = 0;
    int end = a.length-1;
    quickSort(a,start,end);
    for(int i = 0;i<a.length;i++){
    System.out.print(a[i]+" ");
    }
    return a;
    }
    public void quickSort(int a[], int start, int end) { 
    int i, j; 
    i = start; 
    j = end; 
    while (i < j) {//查找基准点下标 
    while (i < j && a[i] <= a[j]) 
    // 以数组start下标的数据为key,右侧扫描 
    j--; 
    if (i < j) { // 右侧扫描,找出第一个比key小的,交换位置 
    int temp = a[i]; 
    a[i] = a[j]; 
    a[j] = temp; 
    } 
    while (i < j && a[i] < a[j]) 
    // 左侧扫描(此时a[j]中存储着key值) 
    i++; 
    if (i < j) { // 找出第一个比key大的,交换位置 
    int temp = a[i]; 
    a[i] = a[j]; 
    a[j] = temp; 
    } 
    } 
    if (i - start > 1) { // 递归调用,把key前面的完成排序 
    quickSort(a, start, i - 1); 
    } 
    if (end - j > 1) { 
    quickSort(a, j + 1, end); // 递归调用,把key后面的完成排序 
    } 
    } 
    }

    测试用例:

    package cn.zbvc.test;
    
    import org.junit.Assert;
    import org.junit.Test;
    
    import cn.zbvc.sorting.FastDemo;
    
    public class TestFastDem {
        @Test
        public void testFastDem(){
            
            FastDemo fastDemo = new FastDemo();
            int [] a={12,2,5,6,5,1,30,45,23,9};
            int [] b=fastDemo.fastDem(a);
            int [] excepted={1,2,5,5,6,9,12,23,30,45 };
            Assert.assertArrayEquals(excepted, b);
        }
    
    }

    运行结果:

    1 2 5 5 6 9 12 23 30 45 

  • 相关阅读:
    左偏树
    论在Windows下远程连接Ubuntu
    ZOJ 3711 Give Me Your Hand
    SGU 495. Kids and Prizes
    POJ 2151 Check the difficulty of problems
    CodeForces 148D. Bag of mice
    HDU 3631 Shortest Path
    HDU 1869 六度分离
    HDU 2544 最短路
    HDU 3584 Cube
  • 原文地址:https://www.cnblogs.com/guolun/p/7244577.html
Copyright © 2011-2022 走看看