zoukankan      html  css  js  c++  java
  • 【数据结构与算法】冒泡排序

    记录下冒泡算法的实现。

    public class BubbleSort {
    
        public static void sort(Integer[] array) {
            if (array == null || array.length == 0) {
                return;
            }
    
            for (int bubbleNum = 0; bubbleNum < array.length - 1; bubbleNum++) { // 一次只能将一个元素冒泡到对应的位置,所以要将N-1个元素冒泡
                for (int i = 1; i < array.length - bubbleNum; i++) { // 有N个元素,需要对比N-1次将元素冒泡到对应的位置。但因前面的冒泡已经将M个元素冒泡到最后,所以有M个元素无须对比。(N = array.length,M = bubbleNum)
                    if (array[i - 1] > array[i]) {
                        swap(array, i - 1, i);
                    }
                }
            }
        }
    
        private static void swap(Integer[] array, Integer i, Integer j) {
            Integer temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    
    }
    import org.junit.Test;
    
    
    public class HowToTest {
    
        @Test
        public void c1() {
            Integer[] array = {3,16,1,5,2,18,0,9,20,11};
            BubbleSort.sort(array);
    
            for (int i = 0; i < array.length; i++) {
                System.out.print(array[i] + ", ");
            }
            System.out.println();
        }
    
        @Test
        public void c2() {
            Integer[] array = {99,98,97,96,95,94,93,92,91,101,90,89,88,87,86,85};;
            BubbleSort.sort(array);
    
            for (int i = 0; i < array.length; i++) {
                System.out.print(array[i] + ", ");
            }
            System.out.println();
        }
    
    }
  • 相关阅读:
    bzoj 1017 魔兽地图DotR
    poj 1322 chocolate
    bzoj 1045 糖果传递
    poj 3067 japan
    timus 1109 Conference(二分图匹配)
    URAL 1205 By the Underground or by Foot?(SPFA)
    URAL 1242 Werewolf(DFS)
    timus 1033 Labyrinth(BFS)
    URAL 1208 Legendary Teams Contest(DFS)
    URAL 1930 Ivan's Car(BFS)
  • 原文地址:https://www.cnblogs.com/nick-huang/p/5335046.html
Copyright © 2011-2022 走看看