您的位置:首页 > 其它

基本知识(01) -- 冒泡排序和选择排序

2016-12-31 16:03 239 查看
冒泡排序

  基本思路: 冒泡排序会利用双层循环对需要排序的数列进行若干次遍历,每次遍历都会从前往后依次的比较相邻两个数的大小;如果前者比后者大,则交换它们的位置;这样,经过第一轮比较排序后便可把最大(或者最小)的元素排好,然后再用相同的方法把剩下的元素逐个进行比较,就得到了所要的排序。

下面直接来看看具体的代码:

1 /**
2  * 演示选择排序算法
3  * @author Administrator
4  *
5  */
6 public class SelectSort {
7     public void selectSort(int[] array){
8         int min = 0;
9         for(int i = 0;i < array.length-1;i++){
10             //设置初始的最小的位置
11             min = i;
12             //内层循环:每轮遍历都只是找出要要交互的位置,并没有进行交互
13             for(int j = i+1; j < array.length;j++){
14                 if(array[min] > array[j]){
15                     min = j;
16                 }
17             }
18             swap(array,min,i);
19         }
20     }
21
22     private void swap(int[] array,int aIndex,int bIndex){
23         int temp = array[aIndex];
24         array[aIndex] = array[bIndex];
25         array[bIndex] = temp;
26     }
27
28     public static void main(String[] args) {
29         int[] num = new int[10];
30
31         /*随机生成10个int值*/
32         for(int i = 0;i < 10;i++){
33             num[i] = (int)(Math.random() * 1000);
34             System.out.print(num[i] + " ");
35         }
36
37         SelectSort selectSort = new SelectSort();
38
39         System.out.println("");
40         System.out.println("---------------------------");
41         selectSort.selectSort(num);//第一种排序方式
42         for(int n : num){
43             System.out.print(n + " ");
44         }
45     }
46 }


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐