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] + " ");
    	}
    
    }
    

      

  • 相关阅读:
    Linux操作篇之配置Samba
    Chrome扩展实现网页图片右键上传(以E站图片搜索为例)
    Linux开机自动挂载NFS配置的一个误区
    ffmpeg指令解读海康威视摄像头
    linux服务器性能调优之tcp/ip性能调优
    多线程程序设计中的8条简单原则
    初识文件系统
    socket中的listen到底干了哪些事情?
    ip面向无连接?TCP面向连接?HTTP连接方式?
    网络层和数据链层的区别
  • 原文地址:https://www.cnblogs.com/zsslll/p/5454494.html
Copyright © 2011-2022 走看看