forked from keep-starknet-strange/alexandria
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bubble_sort.cairo
47 lines (45 loc) · 1.14 KB
/
bubble_sort.cairo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//! Bubble sort algorithm
use array::ArrayTrait;
// Bubble sort
/// # Arguments
/// * `array` - Array to sort
/// # Returns
/// * `Array<usize>` - Sorted array
fn bubble_sort_elements<T,
impl TCopy: Copy<T>,
impl TDrop: Drop<T>,
impl TPartialOrd: PartialOrd<T>>(
mut array: Array<T>
) -> Array<T> {
if array.len() <= 1 {
return array;
}
let mut idx1 = 0;
let mut idx2 = 1;
let mut sorted_iteration = 0;
let mut sorted_array = ArrayTrait::new();
loop {
if idx2 == array.len() {
sorted_array.append(*array[idx1]);
if (sorted_iteration == 0) {
break ();
}
array = sorted_array;
sorted_array = ArrayTrait::new();
idx1 = 0;
idx2 = 1;
sorted_iteration = 0;
} else {
if *array[idx1] < *array[idx2] {
sorted_array.append(*array[idx1]);
idx1 = idx2;
idx2 += 1;
} else {
sorted_array.append(*array[idx2]);
idx2 += 1;
sorted_iteration = 1;
}
};
};
sorted_array
}