Bubble sorting and optimization of algorithm Introduction

Article catalog

1, Bubble sorting basis

Bubble sorting is one of the basic sorting algorithms for comparison. Its idea is to compare adjacent elements in pairs, the larger number sinks, and the smaller number rises. In this way, the maximum (small) value will be arranged in a segment after a comparison. The whole process is like bubbling, so it is called bubbling sequence.
The steps of bubble sorting are relatively fixed:
    1 > compare adjacent elements. If the first is bigger than the second, exchange them.
                       .
                  3 > repeat the above steps for all elements, except for the elements that have been sorted (the last element after each sorting), until no pair of numbers need.
   here is a classic gif on the Internet to show the whole process of bubble sorting:

The general implementation code of bubble sorting is as follows:

        int[ ] array=new int[ ]{5,2,3,9,4};
        /*The outer loop is the number of sorting passes, array.length Number of array.length-1 trip */
        for(int i=0;i<array.length-1;i++){
        	/*The internal loop is the number of comparisons, i-th comparison array.length-i times */
            for(int j=0;j<array.length-1-i;j++){
            	 /*Compare adjacent elements, exchange if conditions are met (ascending is left greater than right, descending is opposite) */
                if(array[j]>array[j+1]){
                    int temp=array[j];
                    array[j]=array[j+1];
                    array[j+1]=temp;
                }
            }
        }

2, Bubble sorting optimization

                      . Modify the above code slightly to view the results after each comparison:

        int[ ] array=new int[ ]{5,2,3,9,4};
        /*The outer loop is the number of sorting passes, array.length Number of array.length-1 trip */
        for(int i=0;i<array.length-1;i++){
        	/*The internal loop is the number of comparisons, i-th comparison array.length-i times */
            for(int j=0;j<array.length-1-i;j++){
            	 /*Compare adjacent elements, exchange if conditions are met (ascending is left greater than right, descending is opposite) */
                if(array[j]>array[j+1]){
                    int temp=array[j];
                    array[j]=array[j+1];
                    array[j+1]=temp;
                }
                /*View array elements after each comparison*/
                System.out.println("The first "+(i+1)+" Trip, No "+(j+1)+" Comparison results:");
                for(int k=0;k<array.length;k++){
                    System.out.print(array[k]+" ");
                }
                System.out.println();
            }
        }

   the output of this code is:

Results after the first comparison:
2 5 3 9 4
Results after the first and second comparison:
2 3 5 9 4
Results after the first and third comparison:
2 3 5 9 4
Results after the first and fourth comparison:
2 3 5 4 9
Results after the second and first comparison:
2 3 5 4 9
Results after the second comparison:
2 3 5 4 9
Results after the second and third comparison:
2 3 4 5 9
Results after the third and first comparison:
2 3 4 5 9
Results after the third and second comparison:
2 3 4 5 9
The results of the fourth and first comparison:
2 3 4 5 9

                        .

2.1 first optimization

   the first optimization is based on the above test results. If there is no element movement during a comparison, the next comparison will not be carried out. The specific method is to introduce a boolean variable isSwap in each comparison to determine whether the next comparison is necessary. The sample code is as follows:

        int[ ] array=new int[ ]{5,2,3,9,4};
        /*The outer loop is the number of sorting passes, array.length Number of array.length-1 trip */
        for(int i=0;i<array.length-1;i++){
        	boolean isSwap=false;
        	/*The internal loop is the number of comparisons, i-th comparison array.length-i times */
            for(int j=0;j<array.length-1-i;j++){
            	 /*Compare adjacent elements, exchange if conditions are met (ascending is left greater than right, descending is opposite) */
                if(array[j]>array[j+1]){
                    int temp=array[j];
                    array[j]=array[j+1];
                    array[j+1]=temp;
                    isSwap=true;
                }
                /*View array elements after each comparison*/
                System.out.println("The first "+(i+1)+" Trip, No "+(j+1)+" Comparison results:");
                for(int k=0;k<array.length;k++){
                    System.out.print(array[k]+" ");
                }
                System.out.println();
            }
            /*If the elements have not been exchanged, they are in order and no further comparison will be made*/
            if(!isSwap){
            	break;
            }
        }

The test results are as follows:

Results after the first comparison:
2 5 3 9 4
Results after the first and second comparison:
2 3 5 9 4
Results after the first and third comparison:
2 3 5 9 4
Results after the first and fourth comparison:
2 3 5 4 9
Results after the second and first comparison:
2 3 5 4 9
Results after the second comparison:
2 3 5 4 9
Results after the second and third comparison:
2 3 4 5 9
Results after the third and first comparison:
2 3 4 5 9
Results after the third and second comparison:
2 3 4 5 9

   as can be seen from the above test results, the sorting process has been optimized because there is no fourth comparison. Some people may have a question: "after the second comparison, the array is in order. Why do you want to make the third comparison?"? The reason why there is doubt about this may be that the role of isSwap variable is not clear. The role of this variable is "if there is no exchange in this comparison process, it is not necessary to make the next comparison". In the second comparison process, there is an exchange action, so the third comparison will still be carried out.

2.2 second optimization

                         . In other words, the first optimization method can only be optimized at the level of "trip".
   the second optimization method is to realize the optimization at the "secondary" level. The idea is "record the location of the last exchange, there is no exchange at the back, it must be orderly, and then the next sorting can end from the first comparison to the last recorded location". The example code is:

        int[ ] array = new int[ ]{5,2,3,7,9};
        int position = array.length - 1;
        /*The outer loop is the number of sorting passes, array.length Number of array.length-1 trip */
        for(int i = 0;i<array.length-1;i++){
        	boolean isSwap = false;
        	/*Used to record the location of the last exchange*/
        	int newPosition = 0;
        	/*The internal loop is the number of comparisons, i-th comparison array.length-i times */
            for(int j = 0;j<position;j++){
            	 /*Compare adjacent elements, exchange if conditions are met (ascending is left greater than right, descending is opposite) */
                if(array[j]>array[j+1]){
                    int temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
                    isSwap = true;
                    /*Record the location of the last swap*/
                    newPosition = j;
                }
                /*View array elements after each comparison*/
                System.out.println("The first "+(i+1)+" Trip, No "+(j+1)+" Comparison results:");
                for(int k = 0;k<array.length;k++){
                    System.out.print(array[k]+" ");
                }
                System.out.println();
            }
            /*If the elements have not been exchanged, they are in order and no further comparison will be made*/
            if(!isSwap){
            	break;
            }
            /*The position to be compared in the next comparison*/
            position = newPosition;
        }

The test results are as follows:

Results after the first comparison:
2 5 3 7 9
Results after the first and second comparison:
2 3 5 7 9
Results after the first and third comparison:
2 3 5 7 9
Results after the first and fourth comparison:
2 3 5 7 9
Results after the second and first comparison:
2 3 5 7 9

                        .

2.3 third optimization

                      . Therefore, in bubble sorting, it can also carry out two-way loop, the forward loop moves the largest element to the end of the array, and the reverse loop moves the smallest element to the beginning of the array. This sorting method is also called two-way bubbling sorting and cocktail sorting.
   for this sort optimization, let's start with a simple version:

		while(left < right) {
			/*Find the largest element in the current array and put it on the right*/
		    for(int i = left; i<right; i++) {         
		        if(array[i] > array[i+1]) {
		            temp = array[i];
		            array[i] = array[i+1];
		            array[i+1] = temp;
		        }
		    }
		    right--;
		    /*Find the smallest element in the current array and put it on the left*/
		    for(int j = right; j>left; j--) {        
		        if(array[j]<array[j-1]) {
		            temp = array[j];
		            array[j] = array[j-1];
		            array[j-1] = temp;
		        }
		    }
		    left++;
		}

Of course, this third optimization method can be combined with the previous optimization method. The example code is:

		int[ ] array = new int[ ]{5,2,3,7,9};
        int left = 0;
        int right = array.length - 1;
        /*Last swap location*/
        int lastPosition = 0;    
        /*Flag whether traversal comparison should be ended*/
        boolean isSwap = false;    

        while (left < right) {
        	/*Put the largest element at the end of the array*/
            for (int i = left; i < right; i++) { 
                if (array[i] > array[i+1]) {
                    int temp = array[i];
                    array[i] = array[i+1];
                    array[i+1] = temp;
                    isSwap = true;
                    lastPosition = i;
                }
            }
            /*Take the position of the last swap as the right boundary*/
            right = lastPosition;  
            if (!isSwap) { 
                break;
            }
            isSwap = false;
            
            /*Put the smallest element at the head of the array*/
            for (int i = right; i > left; i--) {
                if (array[i] < array[i-1]) {
                    int temp = array[i];
                    array[i] = array[i+1];
                    array[i+1] = temp;
                    isSwap = true;
                    lastPosition = i;
                }
            }
            /*Take the position of the last exchange as the left boundary*/
            left = lastPosition;  
            if (!isSwap) { 
                break;
            }
            isSwap = false;
        }

Posted by keigowei on Sat, 27 Jun 2020 01:32:53 -0700