java实现冒泡排序法

插入排序

public class InsertionSort {  
    public static void sort(int data[]) {  
        for (int i = 1; i < data.length; i++) {  
            for (int j = i; j > 0; j--) {  
                if (data[j] < data[j - 1]) {  
                    int temp = data[j];  
                    data[j] = data[j - 1];  
                    data[j - 1] = temp;  }  }   }   }  }  

抽象排序方法

 public static void bubbleSort(int[] arr) {
    int i, j, temp, len = arr.length;
    for (i = 0; i < len - 1; i++)
        for (j = 0; j < len - 1 - i; j++)
            if (arr[j] > arr[j + 1]) {
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
    }

具体实现且行数最少

import java.util.Arrays;
public class BubbleSort {
    public static void BubbleSort_Method(int[] arr) {
        int temp;//定义一个临时变量
        for(int i=0;iarr[j+1]){
                    temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;}}}}
    public static void main(String[] args) {
        int arr[] = new int[]{1,6,2,2,5,10,-1,20};
        BubbleSort.BubbleSort_Method(arr);
        System.out.println(Arrays.toString(arr));}}

时空复杂度

java实现冒泡排序法_第1张图片
Paste_Image.png

方法一

主函数中通过BubbleSort类带参数的构造函数执行冒泡排序

import java.util.Arrays;
/**
 * 冒泡排序
 * @author zsy
 *
 */
public class BubbleSort {
    public BubbleSort(int[] arr) {
        int temp;//定义一个临时变量
        for(int i=0;i

方法二

主函数通过调用BubbleSort类的静态方法执行冒泡排序

import java.util.Arrays;
/**
 * 冒泡排序
 * @author zsy
 *
 */
public class BubbleSort {
    public static void BubbleSort_Method(int[] arr) {
        int temp;//定义一个临时变量
        for(int i=0;i

运行结果


Paste_Image.png

你可能感兴趣的:(java实现冒泡排序法)