标签:median middle public quick sort start tar UI use
O(n) worst, O(nlogn) average. Use quickSort
This is quickSort
public class Solution { /** * @param nums: A list of integers. * @return: An integer denotes the middle number of the array. */ public int median(int[] nums) { // write your code here if (nums == null || nums.length == 0) { return 0; } quickSort(nums, 0, nums.length - 1); return nums[(nums.length - 1) / 2]; } private void quickSort(int[] nums, int start, int end) { if (start >= end) { return; } int left = start; int right = end; int pivot = nums[start + (end - start) / 2]; while (left <= right) { while (left <= right && nums[left] < pivot) { left++; } while (left <= right && nums[right] > pivot) { right--; } if (left <= right) { int tmp = nums[left]; nums[left] = nums[right]; nums[right] = tmp; left++; right--; } } quickSort(nums, start, right); quickSort(nums, left, end); } }
标签:median middle public quick sort start tar UI use
原文地址:http://www.cnblogs.com/codingEskimo/p/6914948.html