当前位置: 移动技术网 > IT编程>开发语言>Java > 数组排序算法

数组排序算法

2018年02月23日  | 移动技术网IT编程  | 我要评论

英国脱欧影响,保定兼职,邯郸哈牛网

数组排序算法

(一)冒泡排序

基本思想:对比相邻的元素值,如果满足条件就交换元素值,把较小的元素移动数组前面,较大的元素移动到数组后面
算法:
冒泡算法由双层循环实现,其中外层循环控制排序轮次,一般为排序的数组长度减一。而内层循环主要用于对比数组中每个临近元素的大小,以确定是否交换位置,对比和交换的次数随排序轮数而减少。

算法实现:

 1 public class Bubble {
 2     public static void main(String[] args){
 3         int[] array ={63,4,24,1,3,15};
 4         Bubble sorter = new Bubble();
 5         sorter.sort(array);
 6     }
 7     //冒泡排序
 8     public void sort(int[] array){
 9         for(int i=1;i<array.length;i++){  //排序轮次,数组长度-1
10             for(int j=0;j<array.length-i;j++){ //内层比较,每过一轮末尾少比较一个
11                 if(array[j]>array[j+1]){
12                     int temp =array[j];
13                     array[j]=array[j+1];
14                     array[j+1]=temp;
15                 }
16             }
17         }
18         showArray(array);
19     }
20     //显示数组元素
21     public void showArray(int[] array){
22         for(int i:array){
23             System.out.print(i+" ");
24         }
25     }
26 }

 

(二)直接选择排序

速度比冒泡排序快一些
基本思想:将指定排序位置与其他数组元素分别对比,如果满足条件就交换元素值。
举例:
初始值:63 4 24 1 3 15
第一轮:15 4 24 1 3 63
第二轮:15 4 3 1 24 63
第三轮:1 4 3 15 24 63
第四轮:1 3 4 15 24 63
第五轮:1 3 4 15 24 63
解释:首先找出6个数中最大的与最后一个数交换位置,然后在前5个数中找出最大的数与倒数第二个交换位置,这样length-1次

算法实现:

 1 public class Select {
 2     public static void main(String[] args){
 3         int array[]={63,4,24,1,3,15};
 4         Select sorter =new Select();
 5         sorter.sort(array);
 6     }
 7     //直接选择排序
 8     public void sort(int[] array){
 9         int index;
10         for(int i=1;i<array.length;i++){  //排序轮次仍为数组长度-1
11             index=0;
12             for(int j=1;j<=array.length-i;j++){ //内层比较,找出最大数的位置
13                 if(array[j]>array[index]){
14                     index=j;
15                 }
16             }
17             int temp=array[array.length-i];
18             array[array.length-i]=array[index];
19             array[index]=temp;
20         }
21         showArray(array);
22     }
23     //显示数组
24     private void showArray(int[] array) {
25         for(int i:array){
26             System.out.print(i+" ");
27         }
28     }
29 }

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网