Sorting algorithm (four) - bubble sort

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/A1344714150/article/details/88658670

Goal: Use bubble sort method to sort random array.

Thought bubble sort: Suppose there are n elements of an array, then to conduct a total time 1 n-cycles, each cycle, the definition of the variable j starts from index 0, the number is compared with a later, if the Array [j] > array [j + 1] then the switch two numbers, until j == array.length-i-1, into the final completion of the maximum number of tasks, then the next round of cycles; each cycle will compare the current maximum range values pushed to the last minus 1 and Comparative range, the range is 1 until the comparison, the sort is complete.

Code:

	//冒泡排序法
	public static void bubbleSort(int[] array){
		for(int i=0;i<array.length;i++){
			for(int j=0;j<array.length-1-i;j++){
				if(array[j]>array[j+1]){
					int temp = array[j];
					array[j] = array[j + 1];
					array[j + 1] = temp;
				}
			}
		}
	}

Sort Test:

import java.util.Scanner;

public class Client {

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		int n = input.nextInt();
		int left = input.nextInt();
		int right = input.nextInt();
		int[] array = SortUtil.getRandomArrayData(n, left, right);
		System.out.println("排序前:");
		print(array);
		SortUtil.bubbleSort(array);
		System.out.println("排序后:");
		print(array);
	}
	
	public static void print(int[] array){
		for(int i=0;i<array.length;i++){
			System.out.print(array[i]+" ");
		}
		System.out.println();
	}
	
}

Guess you like

Origin blog.csdn.net/A1344714150/article/details/88658670
Recommended