Skip to content

Instantly share code, notes, and snippets.

@levidurfee
Last active April 10, 2017 01:28
Show Gist options
  • Select an option

  • Save levidurfee/2155409bebe2a66585fd3f1548db27af to your computer and use it in GitHub Desktop.

Select an option

Save levidurfee/2155409bebe2a66585fd3f1548db27af to your computer and use it in GitHub Desktop.
bubbles!
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
void show_array(int numbers[], int size);
int main() {
int swap, i, large, small = 0;
int numbers[] = {
90,
80,
10,
70,
55,
43,
5,
500,
499,
1
};
int iteration = 0;
int n = sizeof(numbers) / sizeof(int) - 1;
int max_iteration = (int) pow(n, 2);
printf("Before: \n");
show_array(numbers, n + 1);
do {
for(i=0; i<n; i++) {
if(i >= n) {
continue;
}
if(numbers[i] > numbers[i + 1]) {
large = numbers[i];
small = numbers[i + 1];
numbers[i] = small;
numbers[i + 1] = large;
swap = 1;
}
iteration++;
//printf("i: %i\tmi: %i\n", iteration, max_iteration);
if(iteration >= max_iteration) {
swap = 0;
}
}
} while(swap == 1);
printf("\nAfter: \n");
show_array(numbers, n + 1);
return 1;
}
void show_array(int numbers[], int size) {
int i;
for(i=0; i<size; i++) {
printf("%i\n", numbers[i]);
}
}
class BubbleSort {
static sort(numbers) {
let iteration = 0;
let swap = false;
do {
for(let i=0; i<numbers.length; i++) {
if(!numbers[i + 1]) {
continue;
}
if(numbers[i] > numbers[i + 1]) {
let large = numbers[i];
let small = numbers[i + 1];
numbers[i] = small;
numbers[i + 1] = large;
swap = true;
}
}
iteration++;
if(iteration >= Math.pow(numbers.length, 2)) {
swap = false;
}
}
while(swap);
return numbers;
}
}
let numbers = [
90,
80,
10,
70,
55,
43,
];
console.log('Before', numbers);
numbers = BubbleSort.sort(numbers);
console.log('After', numbers);
<?php
class Fiesta {
public $count;
public function __construct() {
$this->count = 0;
}
public function bubbleSort(array $numbers) {
$swapped = false;
do {
for($i=0;$i<count($numbers);$i++) {
if(!isset($numbers[$i + 1])) {
continue;
}
if($numbers[$i] > $numbers[$i + 1]) {
$large = $numbers[$i];
$small = $numbers[$i + 1];
$numbers[$i] = $small;
$numbers[$i + 1] = $large;
$swapped = true;
}
}
// if count >= O(n^2)
if($this->count >= pow( count($numbers), 2 )) {
$swapped = false;
}
$this->count++;
}
while($swapped);
return $numbers;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment