Java quick sort algorithm, three-way quick sort (Java algorithm and data structure summary notes) [7/20]

1. What is the quick sort algorithm?

        The basic idea of ​​quick sort is to select a reference element (usually the last element) to split the array into two parts, one part is smaller than the reference element, and the other part is greater than the reference element.

        Then recursively sort both parts until the entire array is sorted. This process is implemented through the partition method, which uses two pointers i and j to traverse the array, exchanging elements smaller than the base element to the left and elements larger than the base element to the right.

        ​​​​Finally, put the base element into the correct position and return that position as the dividing point. The time complexity of quick sort is O(nlogn).

As follows: The implementation code of the quick sort algorithm:

import java.util.Arrays;

/**
 * @Description 快速排序算法
 **/
public class QuickSort {

    public static void main(String[] args) {
        int[] array = {0, 8, 9, 5, 6, 1, 4, 9, 3, 6, 3, 8, 2, 1, 7};
        quickSort(array, 0, array.length - 1);
        System.out.println("Sorted array: " + Arrays.toString(array));
    }

    // 递归函数用于执行快速排序
    public static void quickSort(int[] array, int low, int high) {
        if (low < high) {
            // 分割数组并获取基准元素的索引
            int pivotIndex = partition(array, low, high);

            // 递归排序左侧和右侧子数组
            quickSort(array, low, pivotIndex - 1);
            quickSort(array, pivotIndex + 1, high);
        }
    }

    // 函数用于分割数组并返回基准元素的索引
    public static int partition(int[] array, int low, int high) {
        // 选择基准元素(在本例中选择最后一个元素)
        int pivot = array[high];
        int i = low - 1;

        // 遍历数组
        for (int j = low; j < high; j++) {
            if (array[j] < pivot) {
                // 如果元素小于基准元素,则交换位置
                i++;
                swap(array, i, j);
            }
        }

        // 将基准元素放入正确的位置
        swap(array, i + 1, high);

        // 返回基准元素的索引
        return i + 1;
    }

    // 函数用于交换数组中的两个元素
    public static void swap(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

Sorted output:

The above code is an implementation of the quick sort algorithm. In summary, it is:

1. Select a base element (usually the last element in the array). 
2. Split the array into two parts, one part is the elements that are smaller than the base element, and the other part is the elements that are greater than the base element. 
3. Recursively apply the quick sort algorithm to these two parts until each sub-array is sorted. 
4. Combine all subarrays to get the final sorted array. 
 
Specific steps to implement: 
 
1. Select the base element. 
2. Set two pointers, one pointing to the starting position of the array (usually low), and the other pointing to the end position of the array (usually high). 
3. Starting from the starting position, move the pointer to the right until you find an element that is greater than or equal to the base element. 
4. Starting from the end position, move the pointer to the left until you find an element that is less than or equal to the base element. 
5. If the position of the left pointer is smaller than the position of the right pointer, exchange the two elements. 
6. Repeat steps 3 to 5 until the position of the left pointer is greater than or equal to the position of the right pointer. 
7. Exchange the base element with the element pointed to by the left pointer, and place the base element in the correct position. 
8. Recursively apply the quicksort algorithm to the subarrays to the left and right of the base element. 
 
The key to quick sorting is the dividing process, that is, dividing the array into two parts. By continuously dividing and sorting, the entire array is finally sorted. The average time complexity of quick sort is O(nlogn), which is an efficient sorting algorithm.

2. The relationship between quick sort algorithm and three-way quick sort

        The quick sort algorithm and the three-way quick sort algorithm are both sorting algorithms based on the idea of ​​quick sort. The relationship between them is that the three-way quick sort algorithm is an improvement and optimization of the quick sort algorithm. 
 
        The quick sort algorithm divides the array into two parts by selecting a reference element, one part is an element that is smaller than the reference element, and the other part is an element that is greater than the reference element. These two parts are then sorted recursively until the entire array is sorted. 
 
        The three-way quick sort algorithm is improved on the basis of quick sort. It divides the array into three parts by selecting two pivot elements: elements less than the first pivot element, equal to the first pivot element, and elements greater than the first pivot element. Then recursively sort the two parts that are less than and greater than the base element. There is no need to sort the parts that are equal to the base element because they are already in the correct position.  The three-way quick sort algorithm performs better when dealing with arrays containing a large number of repeated elements, because it can handle repeated elements more efficiently and reduce unnecessary comparison and exchange operations. Compared with the quick sort algorithm, the time complexity of the three-way quick sort algorithm is still O(nlogn), but in some cases, its performance is better.  In general, the three-way quick sort algorithm is an improvement on the quick sort algorithm. It improves the efficiency of sorting by reducing the comparison and exchange operations of repeated elements.
 

 

3. Implementation of three-way quick scheduling code

/**
 * @Description 三路快排
 **/
public class ThreeWayQuickSort {

    public static void main(String[] args) {
        int[] array = {9, 8, 5, 9, 2, 9, 1, 2, 3, 4, 6, 8, 4, 7};
        quickSort(array, 0, array.length - 1);
        System.out.println("排序后的数组:");
        for (int num : array) {
            System.out.print(num + " ");
        }
    }

    // 三路快速排序算法
    public static void quickSort(int[] array, int low, int high) {
        if (low < high) {
            // 将数组划分为三部分,并返回等于pivot值的范围
            int[] range = partition(array, low, high);
            // 递归地对小于pivot和大于pivot的部分进行排序
            quickSort(array, low, range[0] - 1);
            quickSort(array, range[1] + 1, high);
        }
    }

    // 划分数组为三部分的函数
    public static int[] partition(int[] array, int low, int high) {
        int pivot = array[low]; // 选择第一个元素作为pivot
        int lt = low; // 初始化lt指针指向low
        int gt = high; // 初始化gt指针指向high
        int i = low + 1; // 初始化i指针指向low的下一个位置

        while (i <= gt) {
            if (array[i] < pivot) {
                swap(array, i, lt);
                i++;
                lt++;
            } else if (array[i] > pivot) {
                swap(array, i, gt);
                gt--;
            } else {
                i++;
            }
        }

        // 返回等于pivot值的范围
        int[] range = {lt, gt};
        return range;
    }

    // 交换数组中两个元素的函数
    public static void swap(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

Sorted output:

Three-way quicksort is an efficient sorting algorithm that sorts an array by dividing it into three parts:

The part less than pivot, the part equal to pivot, and the part greater than pivot.

The following is a summary of the implementation steps of the three-way quick sort algorithm: 
 
1. Select a pivot element (usually the first element of the array). 
2. Initialize three pointers: lt points to the starting position of the array, gt points to the end position of the array, and i points to the position next to the starting position of the array. 
3. Traverse the array starting from i and compare the size relationship between the current element and the pivot: 
   - If the current element is smaller than the pivot, compare it with the element pointed to by the lt pointer Swap and move both the lt and i pointers one bit to the right. 
   - If the current element is greater than pivot, swap it with the element pointed to by the gt pointer, and move the gt pointer one position to the left. 
   - If the current element is equal to pivot, move the i pointer one position to the right. 
4. Repeat step 3 until the i pointer traverses the entire array. 
5. Eventually, the array will be divided into three parts: the part less than pivot, the part equal to pivot, and the part greater than pivot. 
6. Recursively perform a three-way quick sort on the parts smaller than pivot and larger than pivot. 
 
The three-way quick sort algorithm improves the efficiency of sorting by placing equal elements in the middle, thus avoiding repeated comparison and exchange processes.

Guess you like

Origin blog.csdn.net/amosjob/article/details/134254003