7

算法笔记(一)冒泡排序

 2 years ago
source link: https://segmentfault.com/a/1190000040888448
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
冒泡排序算法的原理如下: 

1.比较相邻的元素。如果第一个比第二个大,就交换他们两个。  
2.对每一对相邻元素做同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。 
3.针对所有的元素重复以上的步骤,除了最后一个。  
4.持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
例:对int[] arr = {10,5,9,3,6,8}进行从低到高排序:

冒泡排序

第一轮遍历:
从0-arr.Length-1,使数组中最大的数,冒泡到最高的位置。
第二轮遍历:
从0-arr.Length-2,使数组中次大的数,冒泡到次高的位置。
依次遍历,从到到低依次确认位置。
算法最好时间最坏时间平均时间额外空间冒泡O(n)O(n2)O(n2)0/1

Java代码

public class BubbleSorting {
    public static int[] BubbleSortingFunc(int[] arr) {
        for (int cur = arr.length - 1; cur >= 0; cur--) {
            for (int i = 0; i < cur; i++) {
                if (arr[i]>arr[i+1]) swap(arr, i,i+1);
            }
        }
        return arr;
    }
    //交换数组中两个元素的位置,异或运算的性质,但i不等于j
    public static void swap(int[] arr, int i,int j){
        arr[i] = arr[i] ^ arr[j];
        arr[j] = arr[i] ^ arr[j];
        arr[i] = arr[i] ^ arr[j];
    }
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK