码迷,mamicode.com
首页 > 编程语言 > 详细

数组常见的操作_冒泡排序

时间:2015-02-26 21:34:29      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:

原理:
  相邻的两个元素进行比较,如符合条件换位
  比较一轮后确定了最大角标的元素,第二轮最后一个角标就不用再比较了

 1 public class Array_BubbleSort {
 2     public static void main(String[] args) {
 3         int[] arr = {43,4,89,5,2,-1};
 4 
 5         //Arrays.sort(arr);//java中已经定义好的一种排序方式,开发中,对数组排序,要使用该种方法
 6 
 7 
 8         PrintArray(arr);
 9         bubbleSort(arr);
10         PrintArray(arr);
11     }
12     
13      public static void bubbleSort(int[] arr){ 
14         for (int x =0;x<arr.length-1 ;x++ ){
15             //-x:让每一次比较的元素减少,-1避免角标越界
16             for (int y = 0;y<arr.length-x-1 ;y++ ){
17                 if (arr[y]>arr[y+1]){
18                     swap(arr,x,y+1);
19                 }
20             }
21         }
22     }
23     public static void swap(int[] arr,int a , int b){
24             int temp = arr[a];
25             arr[a] = arr[b];
26             arr[b] = temp;
27     }
28     
29     public static void PrintArray(int[] arr){
30         System.out.print("【");
31         for (int x = 0;x<arr.length ;x++ ){
32             if (x != arr.length-1)
33                System.out.print(arr[x]+", ");
34             else
35                System.out.println(arr[x]+"】");
36         }
37     }
38 }

 

数组常见的操作_冒泡排序

标签:

原文地址:http://www.cnblogs.com/LO-ME/p/3548156.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!