码迷,mamicode.com
首页 > 编程语言 > 详细

数据结构(4)快速排序

时间:2016-01-21 19:08:36      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

快速排序

  • 快速排序原理

快速排序(Quick Sort)的基本思想是,通过一趟排序将待排记录分割成独立的两部分,其中一部分记录的关键字均比另一部分记录的关键字小,则可对这两部分记录继续进行排序,以达到整个序列有序的目的。

  • 主程序
package Sort;

public class QuickSort {
	
	private void Qsort(int[] list, int low, int high){
		int privot;
		if(low < high) {
			print(list);
			/*算出枢轴值privot*/
			privot = Partition(list, low, high);
			/*对低子表递归排序*/
			Qsort(list, low, privot-1);
			/*对高子表递归排序*/
			Qsort(list, privot+1, high);			
		}
	}
	
	private int Partition(int[] list, int low, int high){
		/*用表的第一个记录做枢轴记录*/
		int privotkey = list[low];
		while (low < high){
			while (low < high && list[high] > privotkey)
				high--;			
			/*将比枢轴记录小的记录交换到低端*/
			swap(list, low, high);
			while (low < high && list[low] < privotkey)
				low++;
			/*将比枢轴记录大的记录交换到高端*/
			swap(list, low, high);			
		}
		/*返回枢轴所在的位置*/
		return low;
	}
	
	private void swap(int [] list,int j, int i){
		int temp;
		temp = list[i];
		list[i] = list[j];
		list[j] = temp;
	}	
	
	private void print(int[] data) {
		System.out.println("当前list数组的值:");
		for (int i = 0; i < data.length; i++) {
			System.out.print(data[i] + "\t");
		}
		System.out.println();
	}
	
	public static void main(String[] args) {
		int[] list = {50,40,80,30,60,70,10,90,20};
		QuickSort qs = new QuickSort();
		qs.Qsort(list, 0, list.length-1);
		qs.print(list);
	}
}

  

  • Qsort()分析
	private void Qsort(int[] list, int low, int high){
		int privot;
		if(low < high) {
			print(list);
			/*算出枢轴值privot*/
			privot = Partition(list, low, high);
			/*对低子表递归排序*/
			Qsort(list, low, privot-1);
			/*对高子表递归排序*/
			Qsort(list, privot+1, high);			
		}
	}

  

  • Partition()分析
	private int Partition(int[] list, int low, int high){
		/*用表的第一个记录做枢轴记录*/
		int privotkey = list[low];
		while (low < high){
			while (low < high && list[high] > privotkey)
				high--;			
			/*将比枢轴记录小的记录交换到低端*/
			swap(list, low, high);
			while (low < high && list[low] < privotkey)
				low++;
			/*将比枢轴记录大的记录交换到高端*/
			swap(list, low, high);			
		}
		/*返回枢轴所在的位置*/
		return low;
	}

  

  • 输出结果
当前list数组的值:
50	40	80	30	60	70	10	90	20	
当前list数组的值:
20	40	10	30	50	70	60	90	80	
当前list数组的值:
10	20	40	30	50	70	60	90	80	
当前list数组的值:
10	20	30	40	50	70	60	90	80	
当前list数组的值:
10	20	30	40	50	60	70	90	80	
当前list数组的值:
10	20	30	40	50	60	70	80	90	

  

  • 时间复杂度分析

  最优情况下,快速排序算法的时间复杂度为O(nlogn),空间复杂度也为O(nlogn)

 

数据结构(4)快速排序

标签:

原文地址:http://www.cnblogs.com/danbing/p/5148608.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!