一、数组封装好的排序方法
public static void main(String[] args) {
int[] scores = { 30 , 28 , 33 , 47 , 25 ,21, 88 , 96 } ;
Arrays.sort(scores) ;
System.out.print("scores = { ");
for (int i = 0; i < scores.length; i++) {
if(i<scores.length-1){
System.out.print(scores[i] + ",");
}
if(i==scores.length-1){
System.out.print(scores[i] + " }");
}
}
二、选择排序
选择排序若小到大排序,最先出现的是数组的最小元素出现在第一位,整体思想是用数组的第一个元素开始与数组的每一个元素依次对比,若第一位大于相比较的元素交换元素位子,第一轮比完最小值出现在第一位,然后用第二位依次与后面的元素对比
如下:
public static void main(String[] args) {
int[] scores = { 30 , 28 , 33 , 47 , 25 ,21, 88 , 96 } ;
System.out.print("scores = { ");
for(int i=0 ; i<scores.length; i++){
for(int j=i+1 ; j < scores.length-1 ; j++){
int temp;
//利用临时变量交换元素
if( scores[i] >scores[j]) {
temp = scores[i] ;
scores[i] = scores[j] ;
scores[j] = temp ;
}
}
if(i<scores.length-1){
System.out.print(scores[i] + ",");
}
if(i==scores.length-1){
System.out.print(scores[i] + " }");
}
}
}
三、冒泡排序
冒泡排序,就像水池底部产生气泡往水面山飘,和相邻的相比如前面的元素大于后面的元素,交换位置,最大的元素最先出现在最后一位。 代码如下:
public static void main(String[] args) {
int[] scores = { 30 , 28 , 33 , 47 , 25 , 21 , 88 , 96 , 43} ;
for(int i = 0 ; i<scores.length ; i++){
for(int j = 0 ; j<scores.length-1 ; j++){
int temp ;
//利用临时变量交换元素
if(scores[j] > scores[j+1]){
temp = scores[j] ;
scores[j] = scores[j+1] ;
scores[j+1] = temp;
}
}
}