Skip to content

Instantly share code, notes, and snippets.

@superfunc
Created November 17, 2014 16:39
Show Gist options
  • Save superfunc/3e7ac0f9eac0f6947a7c to your computer and use it in GitHub Desktop.
Save superfunc/3e7ac0f9eac0f6947a7c to your computer and use it in GitHub Desktop.
Bubble sort example
// Sample algorithm, lab 11: bubble sort
// Josh Filstrup, GTA EECS Dept @ KU
// November 17th, 2014
public class bubble {
// A function to swap two elements of an array
public static void swap(int[] xs, int i, int j) {
// Create a temporary value so we don't lose
// it when assigning to xs[i] in the next line.
int tmp = xs[i];
xs[i] = xs[j];
xs[j] = tmp;
}
public static void bubbleSort(int[] xs) {
boolean unsorted = true;
// Keep looping until the array is sorted
while(unsorted) {
unsorted = false;
for(int i = 0; i < xs.length-1; i++) {
// If a number to the left is greater
// than a number to the right, we will
// mark the array as unsorted and swap values
if(xs[i] > xs[i+1]) {
unsorted = true;
swap(xs,i,i+1);
}
}
}
}
public static void main(String[] args) {
// Create a sample array
int[] xs = {1,3,2,4,5};
// Print the original array
for(int i : xs) System.out.println(i);
// Sort the array
bubbleSort(xs);
// Print the sorted version
for(int i : xs) System.out.println(i);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment