快速排序算法java代码实现

package com.haut.gaogeng;
/*
 * 快速排序算法的java代码实现
 */
public class QuickSort {

	
	public static void main(String[] args){
		int[] a = new int[]{15,7,4,1,5,3,9,2,100,55,6,14,55,73};
		//对数组进行全排序
		QSort(a, 0, a.length-1);
		
		//输出数组的元素
		printArray(a);
	}
	

	private static void QSort(int[] a2, int low, int high) {
		//用于记录关键字在排序数组中的位置
		int pivot ;
		//只有low < high时才会有排序的需要
		if(low < high){
			//将数组一分为二,前半部分比关键字小,后半部分比关键字大
			pivot = Partition(a2, low, high);
			
			//对前半部分进递归排序
			QSort(a2, low, pivot - 1);
			//对后半部分进行递归排序
			QSort(a2, pivot + 1, high);
		}
	}


	private static int Partition(int[] a2, int low, int high) {
		int key;
		//将数组a2第一个位置的数作为关键字
		key = a2[low];
		//如果是一个数那就没必要排序了
		while(low < high){
			
			/*如果是循环到low = high没必要执行high--
			 * 从数组后面向前找比关键字小的数的下标
			 * 然后将这位置的数和关键字交换
			 */
			while(low < high && key <= a2[high])
				high--;
			swap(a2, low, high);
			/*如果是循环到low = high没必要执行low++
			 * 从数组前面向后找比关键字大的数的下标
			 * 然后将这位置的数和关键字交换
			 */
			while(low < high && key >= a2[low]){
				low++;
			}
			swap(a2, low, high);
		}
		return low;
	}

	//交换数据
	public static void swap(int[] a2, int low, int high){
	
		int temp = 0;
		temp = a2[low];
		a2[low] = a2[high];
		a2[high] = temp;		
	}
	
	//输出数组的元素
	public static void printArray(int[] a){
		for(int i = 0; i < a.length; i++){
			System.out.println(a[i]);
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值