Skip to content

Instantly share code, notes, and snippets.

@sbsatter
Created August 14, 2016 09:21
Show Gist options
  • Save sbsatter/93d5cee70077457aaf1f8298884f76a2 to your computer and use it in GitHub Desktop.
Save sbsatter/93d5cee70077457aaf1f8298884f76a2 to your computer and use it in GitHub Desktop.
class BubbleSort{
public static void main(String [] args){
int [] unsorted= {9,8,7,6,5,4,3,2,1};
if(args.length!=0){
unsorted= new int [args.length];
for(int i=0; i<args.length; i++){
unsorted[i]=Integer.parseInt(args[i]);
}
}
System.out.println("STARTING SORTING");
int [] sorted= bubbleSort(unsorted);
}
public static int [] bubbleSort(int [] a){
boolean exchanged= true;
for(int passNumber= a.length-1; passNumber>=0; passNumber--){
exchanged=false;
for(int i=0; i< passNumber; i++){
if(a[i]>a[i+1]){
a[i]+=a[i+1];
a[i+1]= a[i]- a[i+1];
a[i]= a[i] - a[i+1];
exchanged=true;
}
if(!exchanged){
return a;
}
}
System.out.println("pass "+ (a.length-passNumber) +": "+printArray(a));
}
return a;
}
public static String printArray(int [] a){
String array="";
for(int i:a){
array+= String.valueOf(i);
array+=" ";
}
return array;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment