• 基础冒泡排序


    import java.util.Arrays;
    
    /**
     * This program demonstrates bubble sort. 冒泡排序的实现方式及优化,个人练习,如有错误请大侠指出
     */
    
    public class BubbleSortImpro {
    
    	public static void main(String[] args) {
    		int[] a = { 3, 5, 10, 4, 1 };
    		bubbleSort1(a);
    		System.out.println("The 1 result: " + Arrays.toString(a));
    
    		int[] b = { 3, 5, 10, 4, 1 };
    		bubbleSort2(b);
    		System.out.println("The 2 result: " + Arrays.toString(b));
    
    		int[] c = { 3, 5, 10, 4, 1 };
    		bubbleSort3(c);
    		System.out.println("The 3 result: " + Arrays.toString(c));
    	}
    
    	// 第一种实现:(前两种实现都是稳定排序)
    	private static void bubbleSort1(int[] arr) {
    		for (int i = 0; i < arr.length - 1; i++)
    			for (int j = 0; j < arr.length - 1 - i; j++) {
    				if (arr[j] > arr[j + 1]) {
    					int temp = 0;
    					temp = arr[j];
    					arr[j] = arr[j + 1];
    					arr[j + 1] = temp;
    				}
    			}
    	}
    
    	// 第二种实现:
    	private static void bubbleSort2(int[] arr) {
    		for (int i = arr.length - 1; i > 0; --i)
    			for (int j = 0; j < i; ++j) {
    				if (arr[j] > arr[j + 1]) {
    					int temp = 0;
    					temp = arr[j];
    					arr[j] = arr[j + 1];
    					arr[j + 1] = temp;
    				}
    			}
    	}
    
    	// 第三种实现;省略了中间的多次交换,这种实现使冒泡排序变成了不稳定排序(参考来的....)
    	private static void bubbleSort3(int[] arr) {
    		for (int i = arr.length - 1, max = 0; i > 0; max = 0, --i) {
    			for (int j = 1; j < i; ++j) {
    				if (arr[j] > arr[max])
    					max = j;
    			}
    			if (arr[max] > arr[i]) {
    				int temp = 0;
    				temp = arr[max];
    				arr[max] = arr[i];
    				arr[i] = temp;
    			}
    		}
    	}
    }
    

    Java初学者



    今天很残酷,明天更残酷,后天很美好
  • 相关阅读:
    大三学习进度64
    大三学习进度70
    中美科技巨头——BATH和GAFA
    多线程写excel数据思路
    3
    1
    比特币
    加分项
    3e
    换题了
  • 原文地址:https://www.cnblogs.com/thinking-better/p/5327351.html
Copyright © 2020-2023  润新知