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
| double findMedianWithQuickSelect(List<int> nums) { int n = nums.length; if (n % 2 == 1) { return quickSelect(nums, 0, n - 1, n ~/ 2).toDouble(); } else { int mid1 = quickSelect(nums, 0, n - 1, n ~/ 2); int mid2 = quickSelect(nums, 0, n - 1, n ~/ 2 - 1); return (mid1 + mid2) / 2.0; } }
int quickSelect(List<int> nums, int left, int right, int k) { if (left == right) return nums[left];
int pivotIndex = partition(nums, left, right);
if (k == pivotIndex) { return nums[k]; } else if (k < pivotIndex) { return quickSelect(nums, left, pivotIndex - 1, k); } else { return quickSelect(nums, pivotIndex + 1, right, k); } }
int partition(List<int> nums, int left, int right) { int pivot = nums[right]; int i = left;
for (int j = left; j < right; j++) { if (nums[j] <= pivot) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; i++; } }
int temp = nums[i]; nums[i] = nums[right]; nums[right] = temp;
return i; }
void main() { List<int> nums = [3, 5, 1, 4, 2]; print("Median is: ${findMedianWithQuickSelect(nums)}"); }
|