You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
//! sort.rspubfninsertion_enhanced_version<T>(arr:&mut[T])whereT:PartialOrd + Copy,{for i in1..arr.len(){let cur = arr[i];letmut j = i - 1;while arr[j] > cur {
arr[j + 1] = arr[j];if j == 0{break;}
j -= 1;}// we exit the loop from that break statementif j == 0 && arr[0] > cur {
arr[0] = cur;}else{// `arr[j] > cur` is not satsified, exit from condition judgement
arr[j + 1] = cur;}}}pubfninsertion_orig_version<T>(arr:&mut[T])whereT:PartialOrd + Copy,{for i in1..arr.len(){let cur = arr[i];letmut j = i - 1;while arr[j] > cur {
arr.swap(j + 1, j);if j == 0{break;}
j -= 1;}}}
You can specify how many items you wanna sort, and choose the algorithm you want, it will give you the time consumed on that:
$ cargo run 10000 orig
Use orig to sort 10000 numbers, consuming 683.218631ms
$ cargo run 10000 enhanced
Use enhanced to sort 10000 numbers, consuming 210.417512ms
$ cargo run 100000 orig
Use orig to sort 100000 numbers, consuming 68.68202042s
$ cargo run 100000 enhanced
Use enhanced to sort 100000 numbers, consuming 20.609979502s
As you can see, we got 3 times better performance:)
And this is the result tested on my machine:
The performance of
insertion sort
can be enhanced by simply move items back instead of swap them:By doing so, we can reduce the number of accesses to array elements by half. To demo this, I wrote a single test:
You can specify how many items you wanna sort, and choose the algorithm you want, it will give you the time consumed on that:
As you can see, we got 3 times better performance:)
And this is the result tested on my machine:
The text was updated successfully, but these errors were encountered: