Skip to content

Commit 6fc0134

Browse files
committed
add: Pancake Sorting
1 parent 1705323 commit 6fc0134

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

β€Ž0969-pancake-sorting.rs

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
struct Solution;
2+
3+
// Two steps to bubble largest values to the end of list to sort:
4+
// 1. Bring value_to_sort to front of list by flipping list until it,
5+
// 2. Move it to the end of list by flipping rest of the list.
6+
//
7+
// Example: [2,1,{4},3]
8+
// -> {4},1,2,3 -> [{3},2,1],4
9+
// -> [1,2],{3},4
10+
impl Solution {
11+
pub fn pancake_sort(mut a: Vec<i32>) -> Vec<i32> {
12+
let mut result = Vec::new();
13+
14+
let largest_value = a.len() as i32;
15+
for value_to_sort in (1..=largest_value).rev() {
16+
let idx = a.iter().position(|&v| v == value_to_sort).unwrap() + 1;
17+
18+
if idx as i32 == value_to_sort {
19+
// value_to_sort is in right place already
20+
continue;
21+
}
22+
23+
if idx != 1 {
24+
// not in front of list already
25+
result.push(idx as i32);
26+
Self::flip(&mut a, idx);
27+
}
28+
29+
result.push(value_to_sort);
30+
Self::flip(&mut a, value_to_sort as usize);
31+
}
32+
33+
result
34+
}
35+
36+
fn flip(a: &mut Vec<i32>, k: usize) {
37+
let mut i = 0;
38+
let mut j = k - 1;
39+
while i < j {
40+
a.swap(i, j);
41+
i += 1;
42+
j -= 1;
43+
}
44+
}
45+
}
46+
47+
fn main() {
48+
assert_eq!(
49+
vec![3, 4, 2, 3, 2],
50+
Solution::pancake_sort(vec![3, 2, 4, 1])
51+
);
52+
assert_eq!(Vec::<i32>::new(), Solution::pancake_sort(vec![1, 2, 3]));
53+
}

0 commit comments

Comments
 (0)