Copyright Notice
- This article original author: Columbia Valley's younger brother
- Author blog address: http://blog.csdn.net/lfdfhl
Principle analysis
There is an unordered array {1,9,7,5,3}, please use bubble sort to sort the array from small to large (large to small).
The first trip: a total of five numbers, compared 4 times, the process is as follows:
1 and 9, 9 is greater, no position change, so it is still 1,9,7,5,3
9 and 7, 9 is greater, need to change Position, 9 and 7 swap 1,7,9,5,3
9 and 5 ratio, 9 is bigger, need to change position, 9 and 5 swap 1,7,5,9,3
9 and 3 ratio, 9 is bigger, need to change Position, 9 and 3 swap 1,7,5,3,9
Second round: 1,7,5,3,9 compared 3 times, the process is as follows:
1 and 7, 7 is bigger, no need to change position, so it is still 1,7,5,3,9
7 and 5 ratio, 7 is big, need to change position, so it becomes 1,5,7,3,9
7 is bigger than 3, 7 is big, need to change position, so it becomes 1,5,3,7,9
The third round: 1,5,3,7,9 compared 2 times, the process is as follows:
1 and 5 ratio, 5 is bigger, no need to change position, so it is still 1,5,3,7,9
5 and 3 ratio, 5 big, need to change position, become 1,3,5,7,9
The fourth round:
1, 3, 5, 7, 9 compared 1 time, the process is as follows: 1 is compared with 3, 3 is larger, no need to change position, so it is still 1,3,5,7,9
summary:
- 1. 5 numbers in the array, compared 5-1=4 times
- 2. How many times did you compare each trip? The number of passes + the number of times compared in this pass = the number of elements in the array
- 3. Compare each time, compare a maximum value and put it at the end
- 4. In each comparison, two numbers are compared in pairs, and the positions may need to be reversed
Code
The code for bubble sort is implemented as follows:
package com.algorithm;
/**
* 本文作者:谷哥的小弟
* 博客地址:http://blog.csdn.net/lfdfhl
*/
public class BubbleSort {
public static void main(String[] args) {
int[] intArray = {
11, 99, 77, 5, 0, -1};
printArray(intArray);
System.out.println();
bubble(intArray);
}
public static void bubble(int[] intArray) {
for (int i = 0; i < intArray.length - 1; i++) {
for (int j = 0; j < intArray.length - 1 - i; j++) {
if (intArray[j] > intArray[j + 1]) {
swap(intArray, j, j + 1);
}
}
}
printArray(intArray);
}
//打印数组
public static void printArray(int[] intArray) {
for (int i = 0; i < intArray.length; i++) {
System.out.print(intArray[i] + " ");
}
}
//交换数组中的元素
public static void swap(int[] intArray, int i, int j) {
int temp = 0;
temp = intArray[i];
intArray[i] = intArray[j];
intArray[j] = temp;
}
}