Skip to content

Commit

Permalink
array: Add ops
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed Aug 9, 2024
1 parent 6f5bed8 commit 914be42
Show file tree
Hide file tree
Showing 7 changed files with 71 additions and 1 deletion.
10 changes: 10 additions & 0 deletions array/src/bin/array-access.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Copyright (c) 2024 Xu Shaohua <[email protected]>. All rights reserved.
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

fn main() {
let numbers: [i32; 6] = [1, 1, 2, 3, 5, 8];
assert_eq!(numbers[0], 1);
assert_eq!(numbers[3], 3);
assert_eq!(numbers[5], 8);
}
18 changes: 18 additions & 0 deletions array/src/bin/array-fill.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright (c) 2024 Xu Shaohua <[email protected]>. All rights reserved.
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

use std::sync::atomic::{AtomicI32, Ordering};

fn get_next_id() -> i32 {
static NEXT_ID: AtomicI32 = AtomicI32::new(1);
NEXT_ID.fetch_add(1, Ordering::Relaxed)
}

fn main() {
let mut numbers = [1, 1, 2, 3, 5];
numbers.fill(0);
assert_eq!(numbers, [0, 0, 0, 0, 0]);
numbers.fill_with(|| get_next_id().pow(2));
assert_eq!(numbers, [1, 4, 9, 16, 25]);
}
10 changes: 10 additions & 0 deletions array/src/bin/array-swap.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Copyright (c) 2024 Xu Shaohua <[email protected]>. All rights reserved.
// Use of this source is governed by General Public License that can be found
// in the LICENSE file.

fn main() {
let mut numbers: [i32; 6] = [1, 1, 2, 3, 5, 8];
assert_eq!(numbers[0], 1);
numbers.swap(0, 5);
assert_eq!(numbers[5], 1);
}
1 change: 1 addition & 0 deletions src/array/assets/array-access.rs
1 change: 1 addition & 0 deletions src/array/assets/array-fill.rs
1 change: 1 addition & 0 deletions src/array/assets/array-swap.rs
31 changes: 30 additions & 1 deletion src/array/ops.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,39 @@
# 数组的基本操作

在 Rust 中, 数组的类型是 `[T; N]`, 其中 `T` 是数组中存放的元素的数据类型, 而 `N` 表示数组的元素个数.
它们一旦被确定后就不能再更改. 另外, 在栈上存储的数组, 其占用的内存大小是在编译期间确定了的,
对栈上数组中的元素的访问效率极高.

## 访问元素

## 修改元素的值
访问数组中的元素, 是通过该元素在数组中的索引值实现的, 该索引值是唯一的.

比如:

```rust
{{#include assets/array-access.rs:5:}}
```

## 交换数组中的两个元素

在进行数组排序时, 经常需要交换其中的元素, 其时间复杂度是 `O(1)`:

```rust
{{#include assets/array-swap.rs:5:}}
```

## 批量填充新的值

如果需要批量修改数组中的元素, 可以使用这个方法:

```rust
{{#include assets/array-fill.rs:5:}}
```

## 搜索

有序数组和元序数组的搜索方式和性能差别很大, 我们放在了 [单独的章节](../search/index.md).

## 排序

数组排序的方法比较多, 我们放在[排序](../sort/index.md) 这一章单独介绍.

0 comments on commit 914be42

Please sign in to comment.