• 排序算法


    简单排序

    冒泡排序

    public class BubbleSort {
    
    	public static void main(String[] args) {
    		ArrayBub a = new ArrayBub(20);
    		a.insert(14);
    		a.insert(144);
    		a.insert(142);
    		a.insert(56);
    		a.insert(23);
    		a.insert(78);
    		a.insert(15);
    		
    		a.display();
    		
    		a.bubbleSort();
    		
    		System.out.println("\nAfter bubble sort:");
    		a.display();
    	}
    }
    
    class ArrayBub
    {
    	private long[] a;
    	private int nElems;
    	
    	public ArrayBub(int max){
    		a = new long[max];
    		nElems = 0;
    	}
    	
    	public void insert(long value){
    		a[nElems] = value;
    		nElems++;
    	}
    	
    	public void display(){
    		for (int i = 0 ; i < nElems; i++){
    			System.out.print(" "+a[i]);
    		}
    	}
    	
    	public void bubbleSort(){
    		int out, in;
    		for (out = nElems-1; out > 0; out--){
    			for (in=0 ; in<out; in++){
    				if (a[in] > a[in+1]){
    					swap(in, in+1);
    				}
    			}
    		}
    	}
    
    	private void swap(int j, int i) {
    		long temp = a[i];
    		a[i] = a[j];
    		a[j] = temp;
    	}
    	
    }

    一般来说,数组中有N个数据项,则第一堂排序中有N-1次比较,第二趟中有N-2次,如此类推。这种序列的求和公式如下:

    (N-1)+(N-2)+(N-3)+.....+1 = N*(N-1)/2

    其时间复杂度为O(n2) ,无论何时,只要看到一个循环嵌套在另一个循环里,例如冒泡排序,选择排序,插入排序,就可以怀疑这个算法的时间复杂度为O(n2) 。外层循环执行N次,内部循环对于每一次外层循环都执行N次(或者几分之N次)。这就意味着将大约需要执行N*N 或者n2次某个操作。

    一个容易计算时间复杂度的方法是:看看有几重for循环,只有一重则时间复杂度为O(n),二重则为O(n2),依此类推,如果有二分则为O(logn),二分例如快速幂、二分查找,如果一个for循环套一个二分,那么时间复杂度则为O(nlogn)。

    高级排序

    归并排序

    高级排序算法都用到了分治算法,也就是分而治之(Divide and Conquer),其平均时间复杂度一般都在O(N*logN)。本归并算法用递归实现。
    递归特点:
    • 调用自身
    • 当调用自身是,是为了解决更小的问题
    • 存在某个足够简单的问题层次,也就是基值终止条件(Base case),以防止无限递归下去,以及由此引发的程序崩溃。
    public class MergeSort {
    	public static void main(String[] args) {
    		int maxSize = 100;
    		DArray arr;
    		arr = new DArray(maxSize);
    
    		arr.insert(64);
    		arr.insert(21);
    		arr.insert(33);
    		arr.insert(70);
    		arr.insert(12);
    		arr.insert(85);
    		arr.insert(44);
    		arr.insert(3);
    		arr.insert(99);
    		arr.insert(0);
    		arr.insert(108);
    		arr.insert(36);
    
    		arr.display();
    
    		arr.mergeSort();
    
    		arr.display();
    	}
    }
    
    class DArray {
    	private long[] theArray;
    	private int nElems;
    
    	// ------------------------
    	public DArray(int max) {
    		theArray = new long[max];
    		nElems = 0;
    	}
    
    	// -----------------------
    	public void insert(long value) {
    		theArray[nElems] = value;
    		nElems++;
    	}
    
    	// ----------------------------
    	public void display() {
    		for (int j = 0; j < nElems; j++)
    			System.out.print(theArray[j] + " ");
    		System.out.println("");
    	}
    
    	// ----------------------
    	public void mergeSort() {
    		long[] workSpace = new long[nElems];
    		recMergeSort(workSpace, 0, nElems - 1);
    	}
    
    	// ----------------------------
    	private void recMergeSort(long[] workSpace, int lowerBound, int upperBound) {
    		if (lowerBound == upperBound)
    			return;
    		else {
    			int mid = (lowerBound + upperBound) / 2;
    			recMergeSort(workSpace, lowerBound, mid);
    			recMergeSort(workSpace, mid + 1, upperBound);
    			merge(workSpace, lowerBound, mid + 1, upperBound);
    		}// end else
    	}// end recMergeSort
    		// -----------------------------
    
    	private void merge(long[] workSpace, int lowPtr, int highPtr, int upperBound) {
    		int j = 0;
    		int lowerBound = lowPtr;
    		int mid = highPtr - 1;
    		int n = upperBound - lowerBound + 1;
    
    		while (lowPtr <= mid && highPtr <= upperBound)
    			if (theArray[lowPtr] < theArray[highPtr])
    				workSpace[j++] = theArray[lowPtr++];
    			else
    				workSpace[j++] = theArray[highPtr++];
    
    		while (lowPtr <= mid)
    			workSpace[j++] = theArray[lowPtr++];
    
    		while (highPtr <= upperBound)
    			workSpace[j++] = theArray[highPtr++];
    
    		for (j = 0; j < n; j++)
    			theArray[lowerBound + j] = workSpace[j];
    	}// end merge()
    		// ------------------------
    }// end class DArray

    快速排序

    1. Choose a pivot value. We take the value of the middle element as pivot value, but it can be any value, which is in range of sorted values, even if it doesn't present in the array.
    2. Partition. Rearrange elements in such a way, that all elements which are lesser than the pivot go to the left part of the array and all elements greater than the pivot, go to the right part of the array. Values equal to the pivot can stay in any part of the array. Notice, that array may be divided in non-equal parts.
    3. Sort both parts. Apply quicksort algorithm recursively to the left and the right parts.
    Example. Sort {1, 12, 5, 26, 7, 14, 3, 7, 2} using quicksort.

    public class QuickSort {
    
    	public static void main(String[] args) {
    		int[] arr = {23,34,56,7,9,36,14,99,108};
    		
    		QuickSort qs  = new QuickSort();
    		display(arr);
    		
    		qs.quickSort(arr, 0, arr.length-1);
    		
    		display(arr);
    		
    	}
    	
    	static void display(int[] arr){
    		for (int i : arr){
    			System.out.print(i+" ");
    		}
    		System.out.println("\n");
    	}
    	
    	int partition(int arr[], int left, int right)
    	{
    	      int i = left, j = right;
    	      int tmp;
    	      int pivot = arr[(left + right) / 2];
    	     
    	      while (i <= j) {
    	            while (arr[i] < pivot)
    	                  i++;
    	            while (arr[j] > pivot)
    	                  j--;
    	            if (i <= j) {
    	                  tmp = arr[i];
    	                  arr[i] = arr[j];
    	                  arr[j] = tmp;
    	                  i++;
    	                  j--;
    	            }
    	      };
    	     
    	      return i;
    	}
    	 
    	void quickSort(int arr[], int left, int right) {
    	      int index = partition(arr, left, right);
    	      if (left < index - 1)
    	            quickSort(arr, left, index - 1);
    	      if (index < right)
    	            quickSort(arr, index, right);
    	}
    }

    参考: http://www.algolist.net/Algorithms/Sorting/Quicksort

    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    tensorflow日志信息如何屏蔽?
    测试图像篡改模型fps逐渐降低的原因?
    np.float32()和np.float64
    hive on spark运行时 ,读取不到hive元数据问题
    Hadoop之HDFS(二)HDFS工作机制和集群安全模式
    Spark中的Driver和Executor详解及相关调优
    Linux查看物理CPU个数、核数、逻辑CPU个数
    shell命令查看进程id,并杀死进程,停止脚本
    Flink CDC 2.0 正式发布,详解核心改进
    Kafka 如何保证消息的消费顺序一致性
  • 原文地址:https://www.cnblogs.com/significantfrank/p/4875834.html
Copyright © 2020-2023  润新知