1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| package quicksort;
public class QuickSort {
private float[] arr ;
public void sort(float[] array) { this.arr = array; quickSort( 0 , array.length - 1); }
public void quickSort(int left, int right) { int pivot = partition(left, right); if (left < pivot - 1) quickSort(left, pivot - 1); else if (pivot < right) quickSort( pivot, right); }
public void findSmallest(float arr[], int k){ quickSort( 0 , arr.length - 1, k); }
private void quickSort( int lefe, int right,int k){
int pivot = partition(lefe, right);
if(pivot == k-1){ System.out.printf("第%d小數為%.2f\n", k, arr[pivot]); } else if (pivot > k-1) quickSort( lefe, pivot-1 , k); else quickSort( pivot, right, k);
}
private int partition(int left, int right) { int i = left, j = right; float tmp; float pivot = arr[(left + right) / 2];
while (i <= j) { while (arr[i] < pivot) i++; while (arr[j] > pivot) j--; if (i <= j) { tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; i++; j--; } };
return i; }
}
|