Java快速排序
快速排序的基本思想:
通过一趟排序将待排序记录分割成独立的两部分,其中一部分记录的关键字均比另一部分关键字小,则分别对这两部分继续进行排序,直到整个序列有序。
先看一下这幅图:
把整个序列看做一个数组,把第零个位置看做中轴,和最后一个比,如果比它小交换,比它大不做任何处理;交换了以后再和小的那端比,比它小不交换,比他大交 换。这样循环往复,一趟排序完成,左边就是比中轴小的,右边就是比中轴大的,然后再用分治法,分别对这两个独立的数组进行排序。
快速排序类:
class QSort { public int[] data; private int partition(int list[], int low, int high) { int key = list[low]; while (high > low) { while (low < high && list[high] > key) high--; list[low] = list[high]; while (low < high && list[low] <= key) low++; list[high] = list[low]; } list[low] = key; return low; } public void sort(int low, int high) { if (low < high) { int result = partition(data, low, high); sort(low, result - 1); sort(result + 1, high); } } public void display() { for (int i = 0; i < data.length; i++) { System.out.print(data[i] + " "); } } }
public class QuickSort { public static void main(String[] args) { QSort qs = new QSort(); int[] data = { 44, 22, 2, 32, 54, 22, 88, 77, 99 }; qs.data = data; qs.sort(0, qs.data.length - 1); qs.display(); } }
快速排序是对冒泡排序的一种改进,平均时间复杂度是O(nlogn)
技术,编程,音乐

浙公网安备 33010602011771号