/*
* 冒泡排序的实现
*
* */
public class Sort {
/*public static void bubble_sort(Integer[] unsorted){
for (int i = 0; i < unsorted.length -1; i++){ //最多做n-1趟排序
for(int j = 0 ;j < unsorted.length - i - 1; j++){ //对当前无序区间score[0......length-i-1]进行排序(j的范围很关键,这个范围是在逐步缩小的)
if(unsorted[j] < unsorted[j + 1]){ //把小的值交换到后面
int temp = unsorted[j];
unsorted[j] = unsorted[j + 1];
unsorted[j + 1] = temp;
}
}
}
}*/
public static void sort(Integer[] unsorted){
Integer temp = 0;
for(int i = 0; i < unsorted.length -1; i++){
for(int j = unsorted.length-1;j>i;j--){
if(unsorted[j] < unsorted[j - 1]){ //把大的值交换到后面
temp = unsorted[j];
unsorted[j] = unsorted[j - 1];
unsorted[j - 1] = temp;
}
}
}
}
public static void main(String[] args) {
Integer[] arr = {1,65,34,23,32};
sort(arr);
for (Integer integer : arr) {
System.out.print(integer+" ");
}
}
}
在此处写冒泡排序只是其中目的之一,最主要的目的是记录在做这个小例子中遇到的问题:
1、sort方法定义为static方法,为什么?不定义会怎样?
主要的目的就是为了在本类的main()中调用。
根据jvm的工作机制可知,静态方法和非静态方法的加载机制是不同的,如果sort是非静态的方法,在静态的main()中只能通过new的方法调用;
在非静态的方法中可通过this.方法名的方式调用。
问题有点绕,感觉这个问题挺重要,理解了对于以后的学习很有好处,希望对你有所帮助!