冒泡排序

来源:互联网 发布:windows sdk编程是啥 编辑:程序博客网 时间:2024/05/22 09:51

冒泡排序:

冒泡排序是一个稳定的排序方法,平均复杂度为O(n^2)。

 基本思想:

 从后往前(或从前往后)两两比较相邻的元素的值,若为逆序(即A[i-1]>A[i]),则交换它们,直到序列比较完。此为一趟冒泡

 结果将最小的元素交换到待排序列的第一个位置。下一趟冒泡时,前一趟确定的最小元素不再参与比较,待排序列减少一个元素,每趟冒泡的结果把

 序列中的最小元素放到了序列的最终位置,最多做n-1趟冒泡就能把所有元素排好序。

下面实现的是从小到大排序

第一种:已知待排序序列的个数

package bubbleSort;


import java.util.Scanner;

public class bubbleSort {

    public static void bubbleSort(int[] number)
    {
        int temp = 0;
        int n = number.length;
        for(int i = 0 ; i < n-1; i ++)
        {
        for(int j = 0 ;j < n-1-i ; j++)
        {
            if(number[j] > number[j+1])  //交换两数位置
            {
            temp = number[j];
            number[j] = number[j+1];
            number[j+1] = temp;
            }
        }
        }
        for(int i=0;i<number.length;i++){
        System.out.print(number[i]+" ");
        }
        System.out.println();
    }
    
    public static void main(String[] args) {
    int n;
    Scanner sc = new Scanner(System.in);
    System.out.println("请输入排序序列个数:");
        n = sc.nextInt();
        int num[] = new int[n];
        for(int i=0;i<n;i++){
        num[i] = sc.nextInt();
        }
        bubbleSort(num);
        
    }
}


第二种:待排序序列的个数未知

package bubbleSort;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;


public class bubble {
public static void bubbleSort(int[] number)
    {
        int temp = 0;
        int n = number.length;
        for(int i = 0 ; i < n-1; i ++)
        {
        for(int j = 0 ;j < n-1-i ; j++)
        {
            if(number[j] > number[j+1])  //交换两数的位置
            {
            temp = number[j];
            number[j] = number[j+1];
            number[j+1] = temp;
            }
        }
        }
        for(int i=0;i<number.length;i++){
        System.out.print(number[i]+" ");
        }
        System.out.println();
    }

    public static void main(String[] args) throws IOException {
//     BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//        String str = br.readLine();
       
        /*int num[] = null;
        if(!str.equals(" ")){
        String stringArray[] = str.split(" ");
        num= new int[stringArray.length];
        for(int i=0;i<stringArray.length;i++){
        num[i] = Integer.parseInt(stringArray[i]);
        }
        }*/        //注释部分是另一种输入实现方式
    Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();
    String arr[] = str.split(" ");
    int num[] = new int[arr.length];
    for(int i=0;i<arr.length;i++){
    num[i] = Integer.parseInt(arr[i]);
    }
bubbleSort(num);
    }
}