【算法】快速排序算法的java实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/diyinqian/article/details/83303852
  1. 快排的核心代码(递归):
	private static void quickSort(int[] a, int i, int j) {if (i < j) {
			int mid = partition(a,i,j);
			quickSort(a, i, mid-1);
			quickSort(a, mid+1, j);
		}
	}
  1. partition函数
	/**
	 *构造分割点,使得分割点左边元素都小于分割点,右边元素都大于分割点。
	 * @param a  待排序数组
	 * @param low 本次寻找分割点的区间中的最小坐标
	 * @param high 本次寻找分割点的区间中的最大坐标
	 * @return 分割点的坐标
	 */
	private static int partition(int[] a, int low, int high) {
		int biao = a[low];
		while(low < high) {
			 while (low < high && a[high] >= biao)
	                high--;
	            if (low < high)
	                a[low++] = a[high];
	            while (low < high && a[low] <= biao)
	                low++;
	            if (low < high)
	                a[high--] = a[low];
		}
		a[low] = biao;
		return low;
	}
  1. 生成指定个数的随机数数组
	private static int[] getRandomArr(int numberCount) {
		int a[] = new int[numberCount];
		for (int i = 0; i < a.length; i++) {
			a[i] = (int) (1+(int)(Math.random()*(numberCount*5-1)));//生成从1~numberCount*5的随机数,这个区间可以自己设置
		}
		return a;
	}

4.main函数:

	public static void main(String[] args) {
		int n = 30;
		int a[] = getRandomArr(n);//数组个数
		System.out.println("defore:");
		System.out.println(Arrays.toString(a));
		quickSort(a,0,n-1);
		System.out.println("after:");
		System.out.println(Arrays.toString(a));
	}
  1. 完整版:
package main.java.test;

import java.util.Arrays;
import java.util.Date;

/**
 * @author 12556
 *
 */
public class QuickSort {

	private static int[] getRandomArr(int numberCount) {
		int a[] = new int[numberCount];
		for (int i = 0; i < a.length; i++) {
			a[i] = (int) (1+(int)(Math.random()*(numberCount*5-1)));
		}
		return a;
	}
	
	

	private static void quickSort(int[] a, int i, int j) {if (i < j) {
			int mid = partition(a,i,j);
			quickSort(a, i, mid-1);
			quickSort(a, mid+1, j);
		}
	}


	/**
	 *构造分割点,使得分割点左边元素都小于分割点,右边元素都大于分割点。
	 * @param a  待排序数组
	 * @param low 本次寻找分割点的区间中的最小坐标
	 * @param high 本次寻找分割点的区间中的最大坐标
	 * @return 分割点的坐标
	 */
	private static int partition(int[] a, int low, int high) {
		int biao = a[low];
		while(low < high) {
			 while (low < high && a[high] >= biao)
	                high--;
	            if (low < high)
	                a[low++] = a[high];
	            while (low < high && a[low] <= biao)
	                low++;
	            if (low < high)
	                a[high--] = a[low];
		}
		a[low] = biao;
		return low;
	}
}

	public static void main(String[] args) {
		int n = 30;
		int a[] = getRandomArr(n);//数组个数
		System.out.println("defore:");
		System.out.println(Arrays.toString(a));
//		long startTime = System.nanoTime();
		quickSort(a,0,n-1);
//		long duration = System.nanoTime()-startTime;
		System.out.println("after:");
		System.out.println(Arrays.toString(a));
//		System.out.println("duration(ms)="+duration/(1000000*1.0));
	}


猜你喜欢

转载自blog.csdn.net/diyinqian/article/details/83303852