java code implementation of exchange sorting of [data structure and algorithm]

Keywords: Algorithm data structure

preface

        Today, I will share with you a very important sorting algorithm among data structures and algorithms. The so-called sorting is to reorder the data elements in ascending and descending order according to the specified keyword size. Sorting is a basic operation of data structures such as linear tables and binary trees. Sorting can improve our search efficiency, Then let's enter the sorting world together

catalogue

1, The idea of exchange sorting

2, Bubble sorting

        2.1 bubble sorting algorithm description

        2.2 implementation of bubble sorting java code

         2.3 bubble sorting algorithm analysis

3, Quick sort

        3.1 quick sort algorithm description

         3.2 implementation of quick sort code

        3.3 summary of quick sort algorithm

1, The idea of exchange sorting

        The idea of exchange sorting: compare the sizes of two elements. If they are in reverse order, that is, they are not sorted according to certain rules, such as ascending order, they are exchanged. There are two algorithms for exchange sorting: bubble sorting and quick sorting.

2, Bubble sorting

        2.1 bubble sorting algorithm description

         Bubble sorting is to compare the size of two adjacent elements. If it is in reverse order, it will be exchanged. If it is sorted in ascending order, the largest element in the data element sequence should be exchanged to the last position each time, that is, the two-phase comparison, and the large element moves backward until the largest element is exchanged to the last position, just like bubbles in the water, so it is called bubble sorting.

         For example, if I want to sort a group of data such as 6,5,4,3,2,1 in ascending order, the first pass should be 5,4,3,2,1,6, that is, when 6 and each element are compared to the final position, it meets our requirements, and the second pass is 4,3,2,1,5,6 until 1,2,3,4,5,6 is sorted.

        2.2 implementation of bubble sorting java code

        Taking the above example as an example, we build a BubbleSort class. Two methods are defined in the class, one swap method for data exchange and one BubbleSort method for bubble sorting algorithm.

        Code example

        I put the explanations in the code in the comments. You can check them by yourself. If you don't understand, you are welcome to discuss them in the comment area

        Bubble class

package com.Sorting.bubblesort;

/**
 * @author wang
 * @packageName com.Sorting.bubblesort
 * @className Bubble
 * @date 2021/11/11 23:24
 */
public class Bubble {
    //Bubble sort
    public static void bubbleSort(int[] arr) {
        //Define a variable to determine whether there is an exchange
        boolean exchange = true;

        //Double layer for loop, outer loop controls whether the next bubbling occurs
        for(int i = 1;i<arr.length && exchange;i++) {
            //If the lower level loop does not enter the if statement, it indicates that there is no exchange, and the outer loop ends
            exchange = false;
            for(int j = 0;j<arr.length-i;j++) {
                //The inner loop compares the sizes of two adjacent elements. If the former element is larger than the latter element, the swap method is called to exchange two numbers
                if(arr[j]>arr[j+1]) {
                    swap(arr,j,j+1);
                    //Exchange occurs
                    exchange = true;
                }
            }
        }
    }
    public static void swap(int[] arr,int i,int j) {
        //Exchange two data
        int temp = arr[j];
        arr[j] = arr[i];
        arr[i] = temp;
    }
}

Test class:  

package com.Sorting.bubblesort;

import java.util.Arrays;

/**
 * @author wang
 * @packageName com.Sorting.bubblesort
 * @className BubbleTest
 * @date 2021/11/11 23:39
 */
public class BubbleTest {
    public static void main(String[] args) {
        int [] arr = {6,2,4,3,5,1};
        Bubble.bubbleSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
/*
Output results
[1, 2, 3, 4, 5, 6]
 */

         2.3 bubble sorting algorithm analysis

 

        Bubble sorting we analyze his two situations:

1. Best case: if the data sequence is sorted, bubble only once, compare n, and the time complexity is O(n)

2. Worst case: if the data is arranged in reverse order or randomly, the data will bubble n-1. Because our last bubble n has been arranged, we need to bubble n-1. You can draw your own picture to understand. The comparison times and movement times are (n-1) + (n-2) +... + 2 + 1; Finally, the time complexity is O(n2). Then our bubble sorting, that is, the closer it is to order, the higher the time efficiency of his algorithm. On the contrary, if my data has thousands and is just in reverse order, my efficiency will be very low. Therefore, although bubble sorting is stable, it will inevitably lead to low efficiency. Then we can learn another advanced sorting method, quick sorting.

3, Quick sort

        3.1 quick sort algorithm description

        Select an element in the data sequence as the reference value. Each trip starts alternately from both ends of the data sequence. Exchange the elements less than the reference value to the front end of the sequence and the elements greater than the reference value to the back end of the sequence. The position between the two becomes the final position of the reference position. At the same time, the sequence will be divided into two subsequences, Quickly sort the two subsequences respectively until the length of the subsequence is 1.

         So let's understand through the diagram

First, we have a set of arrays int[] arr = {6,1,2,3,8,9,4,5,7};

          At present, the array is sorted in this way. We can give a low pointer to point to the first element in the array and a high pointer to point to the last element. First, we compare the value of high 7 with the value of benchmark element 6. If 7 is greater than 6, we move the position of high to the left until the value of high is less than or equal to the value of benchmark element. For example, when 5, we exchange 5 and 6, Make the value of high position 6 and the value of low position 5; Next, start from the low position to the right, and find that the element value is smaller than the reference element value. For example, 5,1,2,3 are smaller than the reference element value 6, so we will move the low value to 8. At this time, 8 > 6, so we should exchange the positions of 8 and 6, because the large elements are always on the right and the small elements are always on the right (in ascending order). Next, we will get such a result

          At this time, our low and high values are still not equal, indicating that the sorting has not been completed. Continue to compare the high value with the value on the left. For the same reason, compare the high value with the benchmark element. If it is greater than 6, the high value will go to the left, and the low value will go to the right. The sorting results are as follows,

 

                  When we continue the next sorting cycle, the results are as follows:

         At this time, when our low value and high value are equal, we exit the loop. At this time, the first sorting has been completed. We find that the array at this time is not sorted in ascending order. At this time, we need to call recursion to sort the array on the left and the array on the right of the benchmark element respectively, and then sort recursively. Then the java version code is implemented as follows

         3.2 implementation of quick sort code

package com.Sorting.quickSort;



/**
 * @author wang
 * @packageName com.Sorting.quickSort
 * @className QSort
 * @date 2021/11/16 22:57
 */
public class QSort {
    public static void main(String[] args) {
        int[] arr = {6,1,2,3,8,9,4,5,7};
        QuickSort(arr,0,arr.length-1);
        for(int i : arr) {
            System.out.print(i + " ");
        }
        
        //Output result: 1 2 3 4 5 6 7 8 9 

    }

    public static void QuickSort(int[] arr,int low,int high) {
        int pivot;
        if(low<high) {
            pivot = partition(arr,low,high);

            //Sort the array on the left of the benchmark value. The benchmark value minus one is to participate in the next sorting from the value at index 0 to the element before the benchmark value
            QuickSort(arr,low,pivot-1);
            //Similarly, the array on the right of the benchmark value is sorted recursively, from the value of the last element after the benchmark value to the value of the last element
            QuickSort(arr,pivot+1,high);
        }
    }

    public static int partition(int[] arr,int low,int high) {

        //Record a key value, such as the first element in the array
        int pivotKey = arr[low];

        //When the low position is less than the high position, the loop ends
        while(low<high) {
            //When the value at high is greater than the value at the reference position, enter the cycle. When the value is less than the reference value, exit the cycle
            while(low<high && arr[high] >= pivotKey) {
                high--;
            }
            //After exiting the loop, the value at high should be exchanged with the value at low, that is, the value at high should be exchanged with the reference value
            swap(arr,low,high);

            //Same as above
            while(low<high && arr[low] <= pivotKey) {
                low++;
            }
            swap(arr,low,high);
        }
        //Returns the location of the keyword. Low and high can be returned here, because when low==high, the loop ends
        return low;
    }

    public static void swap(int[] arr,int i,int j) {
        //Exchange two data
        int temp = arr[j];
        arr[j] = arr[i];
        arr[i] = temp;
    }
}

        3.3 summary of quick sort algorithm

        Quick sort algorithm because the comparison and exchange of keywords are carried out by jumping, so the quick sort algorithm is unstable. When there are many sequence elements to be sorted and the data elements are arranged randomly, the quick sort is quite fast; When there are many elements in the sequence to be sorted and the benchmark value selection is inappropriate, the quick sort is slower.

        Finally, you are welcome to put forward some suggestions in the comment area. There may be many unclear expressions in the article. You are welcome to read it in combination with the diagram and code. Finally, please give a little praise when you pass by. In the next issue, you will continue to bring you some java knowledge. Bye!

 

 

Posted by marq on Tue, 16 Nov 2021 17:05:02 -0800