您的位置:首页 > 编程语言 > Java开发

《Java 编程技巧1001条》 第397+398条:了解和使用快速排序

2017-12-23 10:34 477 查看
 


《Java 编程技巧1001条》第10章 用数组存储数据 第397+398条 了解和使用快速排序

397Understanding Quick Sort
397 弄懂QuickSort(快速排序)

For largearrays, you need an efficient sorting technique. One of the most efficienttechniques is the quick sort. The quick sort technique takes the middle elementof an array and sub-divides the array into two smaller arrays. One array willcontain elements greater thant the middle value of the original array. Conversely,the other array will contain elements that are less than the middle value. Thequick sort will repeat this process for each new array until the final arrayscontain only a single element. At this point, the single element arrays are inthe proper order, as shown in Figure 397.
 对于大的数组,你必须寻找一种有效的排序方法. Quick sort 就是最有效的排序方法之一种. Quick sort 方法计算了位于数组中心的元素,并用它把数组分成两个较小一点的数组, 其中一个包含了比中心元素大的元素,而另一个则包含了比中心元素小的元素.Quick sort重复以上过程,直到最后, 数组只包含一个元素. 到此时,单元素的数组就是排好序的数组,如图397所示. Production:Place figure - quick sort - SGFigure 397 Iterations of a quick sort.图397 Quick sort的叠代过程
 

398 Putting the Quick Sort to Use
398 应用快速排序

In theprevious tip, you learned that the quick sort is an efficient technique thatyou can use to sort an array. The following code demonstrates how to quick sortan array of 1,000 random integers.
在以上TIP中,你已知道了quick sort是一种你可用来对一数组进行排序的有效方法.以下程序说明了怎样为1000个随机整型数数组进行排序:public class arrayQsort {  static void qsort(int array[], int first, int last)    {      int low = first;      int high = last;       if (first >= last)          return;       int mid = array[(first + last)/2];       do {         while (array[low] < mid)             low++;          while (array[high] > mid)             high--;          if (low <= high)           {             int temp = array[low];             array[low++] = array[high];             array[high--] = temp;           }        } while (low <= high) ;      qsort(array, first, high);     qsort(array, low, last);    }   publicstatic void main(String[] args)    {     int array[] = new int[1000];           System.out.println("Before Sort");      for (int i = 0; i < array.length; i++)       {         array[i] = (int)(Math.random() * 1000.0);         System.out.println(array[i]);       }      qsort(array, 0, array.length-1);      System.out.println("After Sort");      for (int i = 0; i < array.length; i++)       {         System.out.println(array[i]);       }    } }
Note: Theprevious quick sort function sorts an array from lowest to highest. To changethe order of the sort, you simply change the comparisons in the while loops, asthe following code illustrates:
注意: 以上的quick sort函数由低到高地为一数组进行排序. 为了改变排序的次序,你只要改变循环中的比较方法,如下所示:while (array[low] > mid) low++; while (array[high] < mid) high--;
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: