算法基础之快速排序

  算法一直是一块短板,今后会陆续写一些常用算法的实现,希望和大家一起探讨学习。
  快速排序是排序算法中最经典的一个,原理就不再赘述了,直接上代码。欢迎大家拍砖指导。
import java.util.Arrays;

/**
 * 快速排序
 * 
 * @author aaron-han
 * 
 */
public class QuickSort {

	public static void main(String[] args) {
		int[] arr = com.utils.Utils.randomIntArray();
		quickSort(arr, 0, arr.length - 1);
		System.out.println(Arrays.toString(arr));
	}

	public static void quickSort(int[] arr, int low, int high) {
		if (low < high) {
			int mid = partition(arr, low, high);
			quickSort(arr, low, mid - 1);
			quickSort(arr, mid + 1, high);
		}
	}

	private static int partition(int[] arr, int low, int high) {
		int pivot = arr[low];
		int i = low;
		int j = high;
		while (i < j) {
			while (i < j && arr[j] >= pivot) {
				j--;
			}
			while (i < j && arr[i] <= pivot) {
				i++;
			}
			if (i < j) {
				swap(arr, i, j);
			}
		}
		swap(arr, low, j);
		return j;
	}

	private static void swap(int[] arr, int i, int j) {
		int temp = arr[j];
		arr[j] = arr[i];
		arr[i] = temp;
	}

}

猜你喜欢

转载自aaron-han.iteye.com/blog/1460105
今日推荐