search
HomeJavajavaTutorialImplement bubble sort algorithm using java

Algorithm Analysis and Improvement of Bubble Sorting

The basic idea of ​​exchange sorting is: compare the keywords of the records to be sorted pairwise, and when it is found that the order of the two records is opposite, the exchange is performed until there is no reverse order. to the record.
The main sorting methods that apply the basic idea of ​​exchange sorting are: bubble sorting and quick sorting.

public class BubbleSort implements SortUtil.Sort{ 
public void sort(int[] data) { 
int temp; 
for(int i=0;i<data.length;i++){ 
for(int j=data.length-1;j>i;j--){ 
if(data[j]<data[j-1]){ 
SortUtil.swap(data,j,j-1); 
} 
} 
} 
}

Bubble sorting

1. Sorting method

Arrange the sorted record array R[1..n] vertically, and look at each record R It is a bubble with weight R.key. According to the principle that light bubbles cannot be under heavy bubbles, the array R is scanned from bottom to top: any light bubble that violates this principle will be "floated" upward. This is repeated until the last two bubbles are the lighter one at the top and the heavier one at the bottom.

(1) The initial

R[1..n] is an unordered area.

(2) The first scan

Compare the weights of two adjacent bubbles from the bottom of the disordered area upwards. If it is found that the lighter one is at the bottom and the heavier one is at the top, swap the two. the location of the person. That is, compare (R[n], R[n-1]), (R[n-1], R[n-2]),..., (R[2], R[1]) in sequence; for each pair Bubble (R[j+1], R[j]), if R[j+1].keyWhen the first scan is completed, the "lightest" bubble floats to the top of the interval, that is, the record with the smallest keyword is placed at the highest position R[1].

(3) The second scan

Scan R[2..n]. When the scan is completed, the "second light" bubble floats to the position of R[2]...
Finally, after n-1 scans, the ordered area R[1..n] can be obtained
Note: The first During i scan, R[1..i-1] and R[i..n] are the current ordered area and unordered area respectively. Scanning is still from the bottom of the disordered area upward to the top of the area. When the scan is completed, the lightest bubble in the area floats to the top position R, and the result is that R[1..i] becomes a new ordered area.

2. Example of bubble sorting process

The process of bubble sorting a file with the keyword sequence 49 38 65 97 76 13 27 49

3. Sorting algorithm

(1) Analysis

Because each sorting adds a bubble to the ordered area, after n-1 sorting times, there will be n-1 bubbles in the ordered area. Bubbles, and the weight of bubbles in the disordered area is always greater than or equal to the weight of bubbles in the ordered area, so the entire bubble sorting process requires at most n-1 sorting operations.
If no exchange of bubble positions is found in a certain sorting pass, it means that all the bubbles in the unordered area to be sorted satisfy the principle of the lighter ones at the top and the heavier ones at the bottom. Therefore, the bubble sorting process can be done here Terminate after sorting. To this end, in the algorithm given below, a Boolean exchange is introduced, and it is set to FALSE before each sorting starts. Set to TRUE if an exchange occurs during sorting. The exchange is checked at the end of each sorting pass. If no exchange has occurred, the algorithm is terminated and the next sorting pass is not performed.

(2) Specific algorithm

void BubbleSort(SeqList R) 
{ //R(l..n)是待排序的文件,采用自下向上扫描,对R做冒泡排序 
int i,j; 
Boolean exchange; //交换标志 
for(i=1;i<n;i++){ //最多做n-1趟排序 
exchange=FALSE; //本趟排序开始前,交换标志应为假 
for(j=n-1;j>=i;j--) //对当前无序区R[i..n]自下向上扫描 
if(R[j+1].key<R[j].key){//交换记录 
R[0]=R[j+1]; //R[0]不是哨兵,仅做暂存单元 
R[j+1]=R[j]; 
R[j]=R[0]; 
exchange=TRUE; //发生了交换,故将交换标志置为真 
} 
if(!exchange) //本趟排序未发生交换,提前终止算法 
return; 
} //endfor(外循环) 
} //BubbleSort

4. Algorithm analysis

(1)算法的最好时间复杂度 
若文件的初始状态是正序的,一趟扫描即可完成排序。所需的关键字比较次数C和记录移动次数M均达到最小值: 
Cmin=n-1 
Mmin=0。 
冒泡排序最好的时间复杂度为O(n)。 
(2)算法的最坏时间复杂度 
若初始文件是反序的,需要进行n-1趟排序。每趟排序要进行n-i次关键字的比较(1≤i≤n-1),且每次比较都必须移动记录三次来达到交换记录位置。在这种情况下,比较和移动次数均达到最大值: 
Cmax=n(n-1)/2=O(n2) 
Mmax=3n(n-1)/2=O(n2) 
冒泡排序的最坏时间复杂度为O(n2)。 
(3)算法的平均时间复杂度为O(n2) 
虽然冒泡排序不一定要进行n-1趟,但由于它的记录移动次数较多,故平均时间性能比直接插入排序要差得多。 
(4)算法稳定性 
冒泡排序是就地排序,且它是稳定的。 
5、算法改进 
上述的冒泡排序还可做如下的改进: 
(1)记住最后一次交换发生位置lastExchange的冒泡排序 
在每趟扫描中,记住最后一次交换发生的位置lastExchange,(该位置之前的相邻记录均已有序)。下一趟排序开始时,R[1..lastExchange-1]是有序区,R[lastExchange..n]是无序区。这样,一趟排序可能使当前有序区扩充多个记录,从而减少排序的趟数。具体算法【参见习题】。 
(2) 改变扫描方向的冒泡排序 
①冒泡排序的不对称性 
能一趟扫描完成排序的情况: 
只有最轻的气泡位于R[n]的位置,其余的气泡均已排好序,那么也只需一趟扫描就可以完成排序。 
【例】对初始关键字序列12,18,42,44,45,67,94,10就仅需一趟扫描。 
需要n-1趟扫描完成排序情况: 
当只有最重的气泡位于R[1]的位置,其余的气泡均已排好序时,则仍需做n-1趟扫描才能完成排序。 
【例】对初始关键字序列:94,10,12,18,42,44,45,67就需七趟扫描。
②造成不对称性的原因 
每趟扫描仅能使最重气泡"下沉"一个位置,因此使位于顶端的最重气泡下沉到底部时,需做n-1趟扫描。 
③改进不对称性的方法 
在排序过程中交替改变扫描方向,可改进不对称性。
JAVA代码:

package Utils.Sort;

/**
*@author Linyco
*利用冒泡排序法对数组排序,数组中元素必须实现了Comparable接口。
*/
public class BubbleSort implements SortStrategy
{
       /**
       *对数组obj中的元素以冒泡排序算法进行排序
       */
       public void sort(Comparable[] obj)
       {
              if (obj == null)
              {
                     throw new NullPointerException("The argument can not be null!");
              }

              Comparable tmp;

              for (int i = 0 ;i < obj.length ;i++ )
              {
                     //切记,每次都要从第一个开始比。最后的不用再比。
                     for (int j = 0 ;j < obj.length - i - 1 ;j++ )
                     {
                            //对邻接的元素进行比较,如果后面的小,就交换
                            if (obj[j].compareTo(obj[j + 1]) > 0)
                            {
                                   tmp = obj[j];
                                   obj[j] = obj[j + 1];
                                   obj[j + 1] = tmp;
                            }
                     }
              }
       }
}

更多用java实现冒泡排序算法相关文章请关注PHP中文网!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does the JVM manage garbage collection across different platforms?How does the JVM manage garbage collection across different platforms?Apr 28, 2025 am 12:23 AM

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Why can Java code run on different operating systems without modification?Why can Java code run on different operating systems without modification?Apr 28, 2025 am 12:14 AM

Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

Describe the process of compiling and executing a Java program, highlighting platform independence.Describe the process of compiling and executing a Java program, highlighting platform independence.Apr 28, 2025 am 12:08 AM

The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.

How does the underlying hardware architecture affect Java's performance?How does the underlying hardware architecture affect Java's performance?Apr 28, 2025 am 12:05 AM

Java performance is closely related to hardware architecture, and understanding this relationship can significantly improve programming capabilities. 1) The JVM converts Java bytecode into machine instructions through JIT compilation, which is affected by the CPU architecture. 2) Memory management and garbage collection are affected by RAM and memory bus speed. 3) Cache and branch prediction optimize Java code execution. 4) Multi-threading and parallel processing improve performance on multi-core systems.

Explain why native libraries can break Java's platform independence.Explain why native libraries can break Java's platform independence.Apr 28, 2025 am 12:02 AM

Using native libraries will destroy Java's platform independence, because these libraries need to be compiled separately for each operating system. 1) The native library interacts with Java through JNI, providing functions that cannot be directly implemented by Java. 2) Using native libraries increases project complexity and requires managing library files for different platforms. 3) Although native libraries can improve performance, they should be used with caution and conducted cross-platform testing.

How does the JVM handle differences in operating system APIs?How does the JVM handle differences in operating system APIs?Apr 27, 2025 am 12:18 AM

JVM handles operating system API differences through JavaNativeInterface (JNI) and Java standard library: 1. JNI allows Java code to call local code and directly interact with the operating system API. 2. The Java standard library provides a unified API, which is internally mapped to different operating system APIs to ensure that the code runs across platforms.

How does the modularity introduced in Java 9 impact platform independence?How does the modularity introduced in Java 9 impact platform independence?Apr 27, 2025 am 12:15 AM

modularitydoesnotdirectlyaffectJava'splatformindependence.Java'splatformindependenceismaintainedbytheJVM,butmodularityinfluencesapplicationstructureandmanagement,indirectlyimpactingplatformindependence.1)Deploymentanddistributionbecomemoreefficientwi

What is bytecode, and how does it relate to Java's platform independence?What is bytecode, and how does it relate to Java's platform independence?Apr 27, 2025 am 12:06 AM

BytecodeinJavaistheintermediaterepresentationthatenablesplatformindependence.1)Javacodeiscompiledintobytecodestoredin.classfiles.2)TheJVMinterpretsorcompilesthisbytecodeintomachinecodeatruntime,allowingthesamebytecodetorunonanydevicewithaJVM,thusfulf

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.