Bubble sorting and optimization of java data structure

Posted by Scottya on Thu, 05 Dec 2019 21:11:03 +0100

The bubble sorting time is expressed as O(N^2) with a large o

Traditional bubble sorting:

/**
* @param total Array length to sort
*/
public void sort(int total){
int num[];
if(total <= 0){
System.out.println("Please enter a positive integer greater than 0");
}else{
num = new int[total];
for (int i = 0 ; i < total; i++){
//Generate a number between random 1 and 100
Random ra =new Random();
num[i] = ra.nextInt(100)+1;
}
System.out.println("The array to sort is:" + Arrays.toString(num));
int sum = 0;
int out,in;
for (out = total - 1; out > 1; out--){
for (in = 0 ; in < out; in++){
sum ++;
if(num[in] > num[in+1]){
int temp = num[in];
num[in] = num[in+1];
num[in+1] = temp;
}
}
}
// Primitive bubble sorting
for(int i = 0; i < total -1 ; i ++){
for (int j = 0 ; j < total -1 ; j++){
sum ++;
if(num[j] > num[j+1]){
int temp = num[j];
num[j] = num[j+1];
num[j+1] = temp;
}
}
}
System.out.println("The sorted array is:" + Arrays.toString(num));
System.out.println("Total usage:" + sum);
}
}

Bubble sorting after optimization:

/**
* @param total Array length to sort
*/
public void sort(int total){
int num[];
if(total <= 0){
System.out.println("Please enter a positive integer greater than 0");
}else{
num = new int[total];
for (int i = 0 ; i < total; i++){
//Generate a number between random 1 and 100
Random ra =new Random();
num[i] = ra.nextInt(100)+1;
}
System.out.println("The array to sort is:" + Arrays.toString(num));
/**Core algorithm:
* Double loop, outer loop is used to control the order of arrangement.
* The inner loop is compared from the first bit all the way back. After one inner loop, the maximum number can be set to the end.
* The outer loop allows the inner loop to continue to sort the array that has not been sorted, and the sorted array does not need to be sorted again.
*/
int sum = 0;
int out,in;
for (out = total - 1; out > 1; out--){
for (in = 0 ; in < out; in++){
sum ++;
if(num[in] > num[in+1]){
int temp = num[in];
num[in] = num[in+1];
num[in+1] = temp;
}
}
}

System.out.println("The sorted array is:" + Arrays.toString(num));
System.out.println("Total usage:" + sum);
}
}

We can see that when the outer circulation changes, the other codes are exactly the same.

So how fast can the optimized algorithm be. We all use the array length of 10 to calculate:

Traditional bubble sorting: 9x9=81 steps,

After optimization, bubble sorting: 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 = 44 steps.

Because of the bubble sorting after optimization, after each row, the last number is the largest, so there is no need to compare.

Topics: Java