View Code
1 public class MySelectionSort { 2 3 // 直接选择排序 4 public void StraightSelectionSort(double[] sorted) { 5 for (int i = 1; i < sorted.length; i++) { 6 int minIndex = findMinIndex(sorted, i); 7 exchange(sorted, i, minIndex); 8 } 9 } 10 11 private void exchange(double[] sorted, int i, int j) { 12 // TODO Auto-generated method stub 13 if (i < sorted.length && j < sorted.length && i < j && i >= 0 && j >= 0) { 14 double temp = sorted[i]; 15 sorted[i] = sorted[j]; 16 sorted[j] = temp; 17 } 18 } 19 20 private int findMinIndex(double[] sorted, int i) { 21 // TODO Auto-generated method stub 22 int minIndex = 1; 23 double minValue = Double.MAX_VALUE; 24 for (int j = i; j < sorted.length; j++) { 25 if (sorted[j] < minValue) { 26 minValue = sorted[j]; 27 minIndex = j; 28 } 29 } 30 return minIndex; 31 } 32 33 //小顶堆 34 public void heapSelectionSort(double[] sorted) { 35 int sortedLen = sorted.length; 36 37 for (int i = sortedLen / 2; i > 0; i--) { 38 heapAdjust(sorted, i, sortedLen); 39 } 40 for (int i = sortedLen; i > 1; --i) { 41 exchange(sorted, 1, i); 42 heapAdjust(sorted, 1, i - 1); 43 } 44 } 45 46 public void heapAdjust(double[] sorted, int start, int end) { 47 if (start < end) { 48 double temp = sorted[start]; 49 // 这个地方j<end与课本不同,j<=end会报错: 50 for (int j = 2 * start; j < end; j *= 2) { 51 if (j + 1 < end && sorted[j] - sorted[j + 1] > 10e-6) { 52 ++j; 53 } 54 if (temp <= sorted[j]) { 55 break; 56 } 57 sorted[start] = sorted[j]; 58 start = j; 59 } 60 sorted[start] = temp; 61 } 62 } 63 64 }