The original bubble sort is relatively time-consuming. Even if an array has become ordered after several rounds of exchanges, for example, the array [2,1,3,4,5,6,7], after the first One round has become orderly, but the stubborn bubbling still has to continue the unnutritious pairwise comparison, thus sacrificing time.
If you use a flag to determine whether the current array is in order, exit the loop if it is in order, which can significantly improve the performance of bubble sort~
Since the time complexity of bubble sort is O(n* n) So when there is more data, it becomes slower and is very unsuitable for sorting big data, so we also used a random array with a length of 800 when testing.
The code is as follows:
package go.derek;
import java.util.*;
public class Sort {
//Bubble sort
public void bubbleSort(int[] arr){
for(int i=0; i
if(arr[j]
arr[j]=arr[j-1];
arr[j-1]=tmp;
}
}
}
}
//Improved version of bubble sort
public void bubbleSort_plus(int[] arr){
boolean flag=true;
for(int i=0;i
for(int j=arr.length-1 ;j>i;j--){
if(arr[j]
int tmp=arr[j];
arr[j]=arr[j -1];
arr[j-1]=tmp;
}
}
}
}
public static void main(String[] args){
Sort s=new Sort();
int[] arr1=new int[800];
for(int i=0;i
}
int[] arr2=new int [800];
for(int i=0;i
}
long n=System.currentTimeMillis() ;
s.bubbleSort_plus(arr1);
long m=System.currentTimeMillis();
System.out.println("Bubble sorting time: "+(m-n)+"ms");
long a=System. currentTimeMillis();
s.bubbleSort_plus(arr2);
long b=System.currentTimeMillis();
System.out.println("Time consuming after optimization: "+(b-a)+"ms");
}
}
After running it multiple times, we found the most obvious result:
Bubble sorting time: 12ms
After optimization, time: 4ms
You can see the importance of this flag~
More bubbling Sorting optimized version, the performance is almost doubled. For related articles, please pay attention to the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools
