@快速排序算法(JAVA)(个人复习)

@快速排序算法(JAVA)
一趟快速排序过程
在这里插入图片描述

一趟快速排序代码
static int[] arr;
public static int quickSort(int l , int h)//一趟快速排序
{

 int temp = arr[l];//每次去第一个作为支点
 while(l < h)
 {
	 while(l< h && arr[h] >= temp )
	 {
		 h--;
	 }
	 if(l < h)
	 {
		 arr[l] = arr[h];
		 l++;
		 
	 }
	 while(l < h && arr[l] < temp)
	 {
		 l++;
	 }
	 if(l < h)
	 {
		 arr[h] = arr[l];
		 h--;
	 }
 }
 arr[l] = temp;
 return l;
}

最后使用递归的方式
在这里插入图片描述
public static void qSort(int l , int h)
{
if(l < h)
{
int i = quickSort(l , h);
qSort(l , i-1);
qSort(i+1,h);

	}
}

下面讨论快速排序的时间和空间复杂度
空间复杂度:
快速排序需要用栈来实现递归过程。递归过程借用二叉树表示,最好情况每次分割均匀,递归树高度为O(log2n),空间复杂度为O(log2n);最坏情况是递归树为单支树,高度为O(n),空间复杂度为O(ln);

时间复杂度:
先分析一趟快速排序:
对于一个有n个元素的待排序列,一趟快速排序需要和支点比较n次左右,所以时间复杂度为O(n);
分析整个快速排序:
最后情况是每次划分后两个子表等长在这里插入图片描述
在这里插入图片描述

最坏情况:
每次分割只得到一个子表(支点基本有序);这样的话快速排序就转换为冒泡排序,时间复杂度为o(n*n);

猜你喜欢

转载自blog.csdn.net/shenweiquanshuai/article/details/84671836
今日推荐