Last active
November 18, 2024 11:43
-
-
Save miguelgrinberg/2a4a6dc8be9efb045d321155cbfc521a to your computer and use it in GitHub Desktop.
Bubble sort benchmark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const bubble_sort = (arr) => { | |
const n = arr.length; | |
for (let i = 0; i < n; i++) { | |
for (let j = 0; j < n - i - 1; j++) { | |
if (arr[j] > arr[j + 1]) { | |
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; | |
} | |
} | |
} | |
return arr; | |
} | |
const getRandomInt = max => { | |
return Math.floor(Math.random() * max); | |
} | |
const n = parseInt(process.argv[2]); | |
arr = Array.from({length: n}, _ => getRandomInt(n)); | |
bubble_sort(arr); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import sys | |
def bubble_sort(arr): | |
n = len(arr) | |
for i in range(n): | |
for j in range(0, n-i-1): | |
if arr[j] > arr[j+1]: | |
arr[j], arr[j+1] = arr[j+1], arr[j] | |
return arr | |
if __name__ == '__main__': | |
n = int(sys.argv[1]) | |
arr = [random.randint(0, n - 1) for _ in range(n)] | |
bubble_sort(arr) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::env; | |
use std::fs::File; | |
use std::io::Read; | |
fn bubble_sort(arr: &mut Vec<u32>) -> &mut Vec<u32> { | |
let n: usize = arr.len(); | |
for i in 0..n { | |
for j in 0..n-i-1 { | |
if arr[j] > arr[j+1] { | |
arr.swap(j, j+1); | |
} | |
} | |
} | |
return arr; | |
} | |
pub fn main() { | |
let args: Vec<String> = env::args().skip(1).collect(); | |
let n: u32 = args[0].parse().unwrap(); | |
let mut arr: Vec<u32> = Vec::new(); | |
let mut f = File::open("/dev/urandom").unwrap(); | |
let mut buf = [0u8; 4]; | |
for _ in 0..n { | |
f.read(&mut buf).unwrap(); | |
arr.push(u32::from_ne_bytes(buf) % n); | |
} | |
bubble_sort(&mut arr); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment