Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated Binary Search docs to show insert into an already sorted list #61742

Closed
wants to merge 2 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/libcore/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1362,6 +1362,23 @@ impl<T> [T] {
/// let r = s.binary_search(&1);
/// assert!(match r { Ok(1..=4) => true, _ => false, });
/// ```
///
/// Inserts a new element into already sorted array while maintaining sorted
/// order. Then asserts that the item was inserted correctly.
///
/// ```
/// let mut s = vec![0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55];
/// let num = 14;
///
/// match s.binary_search(&num) {
/// Ok(_) => {}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, I think we should be inserting regardless of finding the item here, so filling out this Ok branch with an insert as well would be good, perhaps even illustrating that by doing something like Ok(idx) | Err(idx) => s.insert(idx, num) in an if let.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe my new commit is more what you were looking for. Do I need to squash the commits or will the merge do that for me?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You'll need to squash the commits; it also looks like you have a build failure here -- I suspect the ; after the if let.

/// Err(pos) => {
/// s.insert(pos, num);
/// }
/// };
///
/// assert_eq!(s[10], num)
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn binary_search(&self, x: &T) -> Result<usize, usize>
where T: Ord
Expand Down