Java实现常见的排序算法之快排(快速排序)

对于快排,无论是看别人面经,还是自己亲身的笔试面试经历,都是经常会遇到的。所以在此,本人仅通过博客的形式记录下来,以便自己查阅,或给其他有需要的人用作参考也好。

public class SortMethods {

	/**
<span style="white-space:pre">	</span> * @author PursueCloud
<span style="white-space:pre">	</span> * 常见排序算法
<span style="white-space:pre">	</span> * 当数据基本无序:①8, 5, 7, 1, 99, 44, 78, 22(比较次数16次)
<span style="white-space:pre">	</span> *数据换成基本有序的数组时,比较次数会增加,如:
<span style="white-space:pre">	</span> *<span style="white-space:pre">				</span>  ②5, 1, 8, 7, 22, 44, 78, 99(18次)
<span style="white-space:pre">	</span> *<span style="white-space:pre">				</span>  ③1, 5, 7, 8, 22, 44, 78, 99(28次)
<span style="white-space:pre">	</span> */<span style="white-space:pre">	</span>
	public static void main(String[] args) {
		int[] testData = {8, 5, 7, 1, 99, 44, 78, 22};
		int[] dataSorted = quickSort(testData, 0, testData.length-1);
		for(int a : dataSorted) {
			System.out.print(a + " ");
		}
		System.out.println("比较次数:" + cnt);
	}
	/**
     * 快速排序
     */
	static int cnt = 0;
	private static int partition(int[] data, int low, int high) {
		int key = data[low];
		while(low < high) {
			while(low<high && data[high]>=key) {
				high--;
				cnt++;
			}
			data[low] = data[high];//(此时因low=high或data[high]<key)将high下标处的数赋给low下标处的数,保证data[low]<key
			while(low<high && data[low]<=key) {
				low++;
				cnt++;
			}
			data[high] = data[low];//(此时因low=high或data[low]>key)将low下标处的数赋给high下标处的数,保证data[high]>key
		}
		data[low] = key;
		return low;
	}
	public static int[] quickSort(int[] data, int low, int high) {
		if(low < high) {
			int result = partition(data, low, high);
			quickSort(data, low, result-1);//对low到result-1下标间数进行排序
			quickSort(data, result+1, high);//对result+1到high下标间数进行排序
		}
		return data;
	}

快排的时间复杂度,最好的情况下是O(nlgn),最坏的情况下位O(n^2)。当待排序数据基本无序时,快排的速度是最快的,而当数据是基本有序时,其反而是最慢的。如上,虽然可能通过累加比较次数的方法来比较其在数据有序或无序的不同情况下的时间复杂度可能有点不严谨,不过对我来说是最直观的。如上面通过排序不同数据得出的结果,数据为基本无序的数据①时cnt的值为16,基本有序的数据②为18,已经排序完毕的③时为28,这个结果也证实了前面所说:“”当待排序数据基本无序时,快排的速度是最快的,而当数据是基本有序时,其反而是最慢的。”

PS:以上若有不妥,谢谢指出


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值