简体   繁体   中英

Given an unordered array of integers print the median value

Given an unordered array of values (zero or positive integers), find the median positive value.

Steps:

Sort array putting 0s at the start Sort elements after the 0s into numeric order

Run two for loops (i++ and j+2) to find the middle element Print value

Is this correct?

Notes: must do this in place, no copying arrays array.length functions not allowed

Yes, it is correct. You just have to be careful to compute correctly the median in arrays of even size. But it's not the best algorithm possible. This algorithm is O(n log n), bounded by the array sorting.

Another option is to implement a quickselect with median of medians to achieve an O(n) complexity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM