Home >Java >javaTutorial >Implement bubble sort algorithm using java

Implement bubble sort algorithm using java

高洛峰
高洛峰Original
2017-01-17 11:48:411667browse

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