Common Code segment (2) Java Implementation of the Bubble Sorting Algorithm and java Algorithm
Common Code segment (2) Java Implementation of the Bubble Sorting Algorithm
Basic Idea of the bubble sort algorithm:
Assume that there are 5 elements in the array. Compare element 2, 3, 4, and 5 with element 1 in sequence. If the number is smaller than element 1, the position is swapped;
Compare element 3, 4, and 5 with element 2 in sequence. If the element is smaller than element 2, the position is swapped... And so on
Example: Array {5, 4, 3, 2, 1}
Compare element 2 with element 1. If the value is smaller than or equal to the value, the value is exchanged. Result 4 5 3 2 1
Compare element 3 with element 1, which is less than true and interchangeable. Result 3 5 4 2 1
Compare element 4 with element 1. If the value is smaller than or equal to the value, the value is exchanged. Result 2 5 4 3 1
Compare element 5 with element 1. If the value is smaller than or equal to the value, the value is interchangeable. Result 1 5 4 3 2
Compare element 3 with element 2. If the value is smaller than or equal to the value of 1, result 1 4 5 3 2.
Compare element 4 with element 2. If the value is smaller than or equal to the value of 1, The result 1 is 3 5 4 2.
Compare element 5 with element 2. If the value is smaller than or equal to the value of 1, result 1 2 5 4 3.
Compare element 4 with element 3. If the value is smaller than or equal to the value of 1, result 1 2 4 5 3.
Compare element 5 with element 3, which is less than true and interchangeable. Result 1 2 3 5 4
Compare element 5 with element 4. If the value is smaller than or equal to the value of 1, result 1 2 3 4 5.
Code:
// Bubble sort public class MaoPao {public static void main (String [] args) {// TODO Auto-generated method stub // Initialize an Int array // time complexity 2/n (n-1), where n is the array length int [] array = {5, 4, 3, 2, 1}; int temp = 0; for (int j = 0; j <array. length-1; j ++) {for (int I = j; I <array. length; I ++) {if (array [I] <= array [j]) {temp = array [j]; array [j] = array [I]; array [I] = temp ;}}for (int k = 0; k <array. length; k ++) {System. out. print (array [k]) ;}}
Time Complexity: 2/n * (n-1), where n is the length of the array.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.