Java Bubble Sorting Algorithms Explain and Improve a little Classroom (Multi-shore College)

Keywords: Java less

Java Bubble Sorting

Overview of Sorting Algorithms

The so-called sorting is to make a series of records, according to the size of one or some of the keywords, increase or decrease the ranking operation. Sorting algorithm is a method of arranging records according to requirements. Sorting algorithms have received considerable attention in many fields, especially in the processing of large amounts of data.

Stability: A sorting algorithm is stable, that is, when there are two keywords R and S with equal records, and before R appears in S in the original list, R in the sorted list will also be before S.

What's the advantage if the algorithm is stable? If the sorting algorithm is stable, then sorting from one key, and then sorting from another key, the results of the first key sorting can be used for the second key sorting. The cardinal sorting is like this, first sorted by low position, and then by high position. The same elements in low position will not change when the same elements in high position are in the same order.

The sorting algorithm can be divided into internal sorting and external sorting according to whether external memory is accessed or not.

Internal sorting refers to the sorting process in which the sorting column is stored in memory completely, and it is suitable for the less large element sequence.

External sorting refers to the sorting of large files, that is to say, the records to be sorted are stored in external memory, and the files to be sorted can not be loaded into memory at one time. In order to achieve the purpose of sorting the whole file, it is necessary to exchange data between memory and external memory for many times.

The sort we are discussing now is internal sort.

Bubble sort

Bubble sorting is inefficient, but the algorithm is simple to implement, so it is very suitable as an entry-level algorithm to study sorting.

basic thought

For all the numbers in the range that have not been sorted out at present, the two adjacent numbers are compared and adjusted from top to bottom, so that the larger number sinks and the smaller number rises upwards. That is, whenever two adjacent numbers are compared and their ranking is found to be contrary to the ranking requirements, they are exchanged. Each traversal determines a maximum value to be placed at the end of the array to be rowed. The next traversal, the maximum value and the elements after it are no longer sorted (already arranged).

java implementation

public class Sort{  
   
  private int [] array;  
  public Sort(int [] array){  
     this.array = array;  
  }  
   
  //Print elements in an array in sequence  
  public void display(){  
     for(int i=0;i<array.length;i++){  
         System.out.print(array[i]+"\t");  
     }  
     System.out.println();  
  }  
   
  //Bubble sort  
  public void bubbleSort(){  
     int temp;  
     int len = array.length;  
     for(int i=0;i<len-1;i++){  //Outer loop: Each cycle determines a relative maximum element  
         for(int j=1;j<len-i;j++){  //Inner cycle: i elements have been arranged, according to i to determine the number of comparisons  
            if(array[j-1]>array[j]){  //If the former bit is larger than the latter bit, exchange position  
                temp = array[j-1];  
                array[j-1] = array[j];  
                array[j] = temp;  
            }  
         }  
         System.out.print("The first"+(i+1)+"Round sorting results:");  
         display();  
     }  
  }  	   
}  

Test:

public static void main(String[] args) {  
     int [] a = {1,5,4,11,2,20,18};  
     Sort sort = new Sort(a);  
     System.out.print("Outcomes without sorting:");  
     sort.display();  
     sort.bubbleSort();  
}  

Print results:

algorithm analysis

In the example above, there are seven numbers in the array to be arranged. Six comparisons are made in the first round of sorting, five comparisons are made in the second round of sorting, and one comparison is made in the last round of sorting. When the total number of elements is N, the total number of comparisons required is:

(N-1)+ (N-2)+ (N-3)+ ...1=N*(N-1)/2

In this way, the algorithm is compared about N2/2 times. Because data is exchanged only when the former element is larger than the latter, the number of exchanges is less than the number of comparisons. If the data is random and about half of the data needs to be exchanged, the number of exchanges is N2/4 (but in the worst case, when the initial data is in reverse order, each comparison needs to be exchanged).

The number of swaps and comparisons is proportional to N2. Because the constants are ignored in the large O representation, the time complexity of bubble sorting is O(N2). The time complexity of O(N2) is a relatively bad result, especially in the case of large amounts of data. So bubble sorting is not usually used in practical applications.

Improvement of Bubble Sorting

As has been analyzed above, the efficiency of bubble sorting is relatively low, so we need to improve it by various methods.

The simplest improvement method is to add a token variable exchange to indicate whether there is data exchange in a sorting process. If there is no data exchange in a sorting process, it means that the data has been arranged according to the requirements, and the sorting can be completed immediately to avoid unnecessary comparison process.

In the example above, after the fourth round of sorting, the whole array is actually ordered, and the last two rounds of comparison are unnecessary.

The improved code is as follows:

  //Bubble Sorting Improvement 1  
  public void bubbleSort_improvement_1(){  
     int temp;  
     int len = array.length;  
      
     for(int i=0;i<len-1;i++){   
         boolean exchange = false;  //Setting swap variables  
         for(int j=1;j<len-i;j++){   
            if(array[j-1]>array[j]){  //If the former bit is larger than the latter bit, exchange position  
                temp = array[j-1];  
                array[j-1] = array[j];  
                array[j] = temp;  
                 
                if(!exchange) exchange =true;  //Exchange operation occurred  
            }  
         }  
         System.out.print("The first"+(i+1)+"Round sorting results:");  
         display();  
         if(!exchange) break;  //If the exchange of data did not occur in the previous round, it proves that the order is already in order. End the sorting.  
     }  
   }

Using the same initial array test, the print results are as follows:

The above improvement method is based on whether data exchange has occurred in the last round of sorting as a mark. Further thinking, if only a few elements in the last round of sorting did not occur data exchange, can we determine whether this section need not be compared? The answer is yes.

For example, in the example above, the ranking results of the first four rounds are as follows:

Result without sorting: 154 11 2 20 18
 The first round of ranking results: 145 2 11 18 20
 Round 2 ranking results: 142 5 11 18 20
 Round 3 ranking results: 1 245 11 18 20
 Round 4 ranking results: 1 24 5 11 18 20

After the first round of sorting, 11, 18, 20 have been ordered, and their positions have not changed after the last several sorting, but according to the bubble algorithm, 18 will still participate in the second round of comparison, 11 will still participate in the second and third round of comparison, in fact, they are all useless.

We can further improve the algorithm: set a pos pointer, the data after pos did not exchange in the previous round of sorting, the next round of sorting, the data after pos is no longer compared.

The code changes are as follows:

//Bubble Sorting Improvement 2  
public void bubbleSort_improvement_2(){  
   int temp;  
   int counter = 1;  
   int endPoint = array.length-1;  //endPoint represents the last element subscript to be compared  
    
   while(endPoint>0){   
      intpos = 1;  
      for(int j=1;j<=endPoint;j++){    
          if(array[j-1]>array[j]){  //If the former bit is larger than the latter bit, exchange position  
             temp= array[j-1];  
             array[j-1]= array[j];  
             array[j]= temp;  
                  
             pos= j;  //Data exchange occurs between elements with subscript j and elements with subscript j-1  
          }  
      }  
	  //In the next round of sorting, only elements with subscripts less than pos are sorted, and elements with subscripts greater than or equal to pos are arranged.  
      endPoint= pos-1;  
       
      System.out.print("The first"+counter+"Round sorting results:");  
      display();  
   }  
} 

For the algorithm, there is no best, only better. In fact, the above two methods of improvement do not cure the root cause. They are an improvement of "stirring up the soup and stopping the boiling". Now let's make an improvement of "drawing salary from the bottom of the kettle".

The traditional bubble algorithm only determines the maximum value in each sort. We can find the maximum value and the minimum value in each cycle, which can reduce the number of rounds in the sort by half.

The improved code is as follows:

//Bubble Sorting Improvement 3  
public void bubbleSort_improvement_3(){  
   int temp;  
   int low = 0;  
   int high = array.length-1;  
   int counter = 1;  
   while(low<high){   
       
      for(int i=low;i<high;++i){   //Forward bubbling to determine maximum  
          if(array[i]>array[i+1]){  //If the former bit is larger than the latter bit, exchange position  
             temp= array[i];  
             array[i]= array[i+1];  
             array[i+1]= temp;  
          }  
      }  
      --high;  
       
      for(int j=high;j>low;--j){   //Reverse bubbling to determine the minimum  
          if(array[j]<array[j-1]){  //If the former bit is larger than the latter bit, exchange position  
             temp= array[j];  
             array[j]= array[j-1];  
             array[j-1]= temp;  
          }  
      }  
      ++low;  
       
      System.out.print("The first"+counter+"Round sorting results:");  
      display();  
      counter++;  
   }  
} 

This is the end. Thank you for seeing it. I hope I can help you.

Pay attention to the public number and get it free of charge - [java Core Knowledge Points]

	QQ discussion group: 984370849

Students who want to study in depth can join the QQ group discussion, have a full set of resources to share, experience to discuss, yes, we are waiting for you to share each other's stories.

Posted by lordvader on Thu, 05 Sep 2019 00:09:10 -0700