Skip to content

Instantly share code, notes, and snippets.

@kanrourou
Created January 14, 2014 22:27
Show Gist options
  • Save kanrourou/8427153 to your computer and use it in GitHub Desktop.
Save kanrourou/8427153 to your computer and use it in GitHub Desktop.
public class SelectionSort {
public static void sort(Comparable[] a){
int N=a.length;
for(int i=0;i<N;++i){
for(int j=i+1;j<N;++j){
if(less(a[i],a[j])){
exch(a,i,j);
}
}
}
}
public static boolean less(Comparable v,Comparable w){
if(v.compareTo(w)<0) return true;
else return false;
}
public static void exch(Comparable[] a,int i,int j){
Comparable temp=a[i];
a[i]=a[j];
a[j]=temp;
}
public static boolean isSort(Comparable[] a){
for(int i=1;i<a.length;++i){
if(less(a[i-1],a[i]))return false;
}
return true;
}
}
public class Student implements Comparable<Student> {
private int score;
private String name;
public Student(){
score=0;
name="unknow";
}
public Student(int score,String name){
this.score=score;
this.name=name;
}
public String toString(){
return "Score: "+score+" Name: "+name;
}
@Override
public int compareTo(Student that){
if(this.score<that.score) return -1;
else if(this.score>that.score) return 1;
else return 0;
}
}
public class TestSelectionSort {
public static void main(String[] args){
Comparable[] a=new Student[20];
a[0]=new Student(72,"Almin");
a[1]=new Student(78,"Peter");
a[2]=new Student(89,"Bob");
a[3]=new Student(91,"Eric");
a[4]=new Student(56,"Adam");
a[5]=new Student(69,"Alpha");
a[6]=new Student(98,"Allen");
a[7]=new Student(90,"Emily");
a[8]=new Student(79,"Emma");
a[9]=new Student(83,"Yui");
a[10]=new Student(100,"Mikasa");
a[11]=new Student(77,"Max");
a[12]=new Student(85,"Noah");
a[13]=new Student(65,"Kun");
a[14]=new Student(74,"Beta");
a[15]=new Student(76,"Rebeca");
a[16]=new Student(89,"Lifa");
a[17]=new Student(81,"Ben");
a[18]=new Student(70,"Petera");
a[19]=new Student(80,"Run");
SelectionSort.sort(a);
Boolean x=SelectionSort.isSort(a);
System.out.println(x);
int N=a.length;
for(int i=0;i<N;++i){
System.out.println(a[i].toString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment