MCPcopy Create free account
hub / github.com/QMHTMY/RustBook / merge

Method merge

publication/code/chapter07/tim_sort.rs:224–282  ·  view source on GitHub ↗

归并排序

(&mut self)

Source from the content-addressed store, hash-verified

222
223 // 归并排序
224 unsafe fn merge(&mut self) {
225 let mut first_count = 0;
226 let mut second_count = 0;
227 while self.second_pos > self.dest_pos && self.second_pos < self.list_len {
228 debug_assert!(self.first_pos + (self.second_pos - self.first_len) == self.dest_pos);
229 if (second_count | first_count) < MIN_GALLOP {
230 if self.temp.get_unchecked(self.first_pos) > self.list.get_unchecked(self.second_pos) {
231 ptr::copy_nonoverlapping(
232 self.list.get_unchecked(self.second_pos),
233 self.list.get_unchecked_mut(self.dest_pos),
234 1,
235 );
236 self.second_pos += 1;
237 second_count += 1;
238 first_count = 0;
239 } else {
240 ptr::copy_nonoverlapping(
241 self.temp.get_unchecked(self.first_pos),
242 self.list.get_unchecked_mut(self.dest_pos),
243 1,
244 );
245 self.first_pos += 1;
246 first_count += 1;
247 second_count = 0;
248 }
249 self.dest_pos += 1;
250 } else {
251 // Galloping 加速模式
252 second_count = gallop_left(
253 self.temp.get_unchecked(self.first_pos),
254 self.list.split_at(self.second_pos).1,
255 Mode::Forward,
256 );
257 ptr::copy(
258 self.list.get_unchecked(self.second_pos),
259 self.list.get_unchecked_mut(self.dest_pos),
260 second_count,
261 );
262 self.dest_pos += second_count;
263 self.second_pos += second_count;
264
265 debug_assert!(self.first_pos + (self.second_pos - self.first_len) == self.dest_pos);
266 if self.second_pos > self.dest_pos && self.second_pos < self.list_len {
267 first_count = gallop_right(
268 self.list.get_unchecked(self.second_pos),
269 self.temp.split_at(self.first_pos).1,
270 Mode::Forward,
271 );
272 ptr::copy_nonoverlapping(
273 self.temp.get_unchecked(self.first_pos),
274 self.list.get_unchecked_mut(self.dest_pos),
275 first_count,
276 );
277 self.dest_pos += first_count;
278 self.first_pos += first_count;
279 }
280 }
281 }

Callers 2

merge_loFunction · 0.45
merge_hiFunction · 0.45

Calls 4

gallop_leftFunction · 0.85
gallop_rightFunction · 0.85
copy_backwardsFunction · 0.85

Tested by

no test coverage detected