zoukankan      html  css  js  c++  java
  • 排序—快速排序

    快速排序由C.A.R.Hoare(1962) 开发的,该算法在数组中选择一个称为主元(pivot)的元素,将数组分为两部分,是的第一部分中的所有元素都小于或等于主元,而第二部分的所有元素都大于主元。对第一部分递归地应用快速排序算法,然后对第二部分递归地应用快速排序算法。

    package ss.sort;
    /**
     * 快速排序
     * @author zhangss 2016-5-3 11:42:32
     * */
    public class QuickSort {
    	
    	public static void quickSort(int[] list){
    		quickSort(list, 0, list.length - 1);
    	}
    	
    	private static void quickSort(int[] list, int first, int last){
    		if(last > first){
    			int pivotIndex = partition(list, first, last);
    			quickSort(list, first, pivotIndex - 1);
    			quickSort(list, pivotIndex + 1, last);
    		}
    	}
    	
    	private static int partition(int[] list, int first, int last){
    		int pivot = list[first];  // Choose the first element as the pivot
    		int low = first + 1;      // Index for forward search
    		int high = last;          // Index for backward search
    		
    		while(high > low){
    			// Search forward from left
    			while(low <= high && list[low] <= pivot)
    				low++;
    			
    			// Search forward from right
    			while(low <= high && list[high] > pivot)
    				high--;
    			
    			// Swap two elements in the list
    			if(high > low){
    				int temp = list[high];
    				list[high] = list[low];
    				list[low] = temp;
    			}
    		}
    		
    		while(high > first && list[high] >= pivot)
    			high--;
    		
    		// Swap pivot with list[high]
    		if(pivot > list[high]){
    			list[first] = list[high];
    			list[high] = pivot;
    			return high;
    		}else{
    			return first;
    		}
    	}
    	/**
    	 * A test method
    	 */
    	public static void main(String[] args) {
    		int[] list = {2, 3, 2, 5, 6, 1, -2, 3, 14, 12};
    		quickSort(list);
    		for(int i = 0; i < list.length; i++)
    			System.out.print(list[i] + " ");
    	}
    
    }
    

      

  • 相关阅读:
    计蒜客38228 Max answer 单调栈 + 线段树
    Codeforces 103D Time to Raid Cowavans 分块
    Poj 2352 Stars
    HDU 6203 ping ping ping LCA + 贪心
    redis——数据库发展
    数据库拆分
    java基础算法
    docker部署redis集群
    docker网络
    DockerFile
  • 原文地址:https://www.cnblogs.com/zsslll/p/5454494.html
Copyright © 2011-2022 走看看