基础算法2——冒泡排序和快速排序

View Code
 1 public class MyExchangeSort {
 2     // 冒泡排序
 3     public void BubbleExchangeSort(double[] sorted) {
 4         for (int i = 1; i < sorted.length; i++) {//进行排序次数为数组长度-1
 5             for (int j = 0; j < sorted.length - i; j++) {//从上到下进行排序,大数下沉
 6                 if (sorted[j] > sorted[j + 1]) {
 7                     double temp = sorted[j];
 8                     sorted[j] = sorted[j + 1];
 9                     sorted[j + 1] = temp;
10                 }
11             }
12         }
13     }
14     public void BubbleExchangeSort1(double[] sorted) {
15         for (int i = 1; i < sorted.length; i++) {
16             for (int j = sorted.length; j > i+1; j--) {//从下到上进行排序,小数上浮
17                 if (sorted[j] < sorted[j - 1]) {
18                     double temp = sorted[j];
19                     sorted[j] = sorted[j - 1];
20                     sorted[j - 1] = temp;
21                 }
22             }
23         }
24     }
25     // 快速排序
26     public void QucikExchangeSort(double[] sorted, int low, int high) {
27         if (low < high) {
28             int pivot = findPivot(sorted, low, high);
29             QucikExchangeSort(sorted, low, pivot - 1);
30             QucikExchangeSort(sorted, pivot + 1, high);
31         }
32     }
33 
34     private int findPivot(double[] sorted, int low, int high) {
35         // TODO Auto-generated method stub
36         sorted[0] = sorted[low];
37         while (low < high) {
38             while (low < high && sorted[high] > sorted[0])
39                 high--;
40             sorted[low] = sorted[high];
41             while (low < high && sorted[low] < sorted[0])
42                 low++;
43             sorted[high] = sorted[low];
44         }
45         sorted[low] = sorted[0];
46         return low;
47     }
48 
49 }

 

posted @ 2013-05-09 16:04  路人浅笑  阅读(194)  评论(0编辑  收藏  举报