Skip to content

Instantly share code, notes, and snippets.

@denkspuren
Created December 9, 2016 15:08
Show Gist options
  • Save denkspuren/dcef420dc5cd1f972525419b46945fb8 to your computer and use it in GitHub Desktop.
Save denkspuren/dcef420dc5cd1f972525419b46945fb8 to your computer and use it in GitHub Desktop.
Bubblesort the arguments given via the command line
// Usage:
// > java BSort Petra Bob Peter Adam Zap John Adam
// Adam Adam Bob John Peter Petra Zap
class BSort {
public static void main(String[] args) {
bubbleSortSmart(args);
for(String arg : args) System.out.print(arg + " ");
System.out.println();
System.exit(0);
}
static void bubbleSortSmart(String[] a) {
int newIdx = a.length - 1;
int oldIdx = 0;
while(newIdx != oldIdx) {
oldIdx = newIdx;
for(int i = 0; i < oldIdx; i++) {
if (a[i].compareTo(a[i+1]) > 0) {
String tmp = a[i];
a[i] = a[i+1];
a[i+1] = tmp;
newIdx = i;
}
}
}
}
static void bubbleSortNaive(String[] a) {
int maxIdx = a.length - 1;
while(maxIdx != 0) {
for(int i = 0; i < maxIdx; i++) {
if (a[i].compareTo(a[i+1]) > 0) {
String tmp = a[i];
a[i] = a[i+1];
a[i+1] = tmp;
}
}
maxIdx--;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment