Implementation and optimization of quick sort

1. One-way scanning of segmentation operation

public class QuickSort {
    public int partition(int[] a, int left, int right) {
        int temp, pivot;//pivot存放主元
        int i, j;
        pivot = a[right];
        i = left;
        for (j = left; j < right; j++) {
            if (a[j] < pivot) {
                //交换值
               temp = a[i];
               a[i] = a[j];
               a[j] = temp;
               i++;
            }
        }
        a[right] = a[i];
        a[i] = pivot;
        return i;//把主元的下标返回
    }

    public void quickSort(int[] a, int left, int right) {
        int center;
        if (left < right) {
            center = partition(a, left, right);
            quickSort(a, left, center - 1);//左半部分
            quickSort(a, center + 1, right);//右半部分
        }
    }
}

2. Bidirectional scanning for segmentation operation

 private int partition2(int[] a, int left, int right) {
        int i, j;
        int pivot = a[left];
        i = left + 1;
        j = right;
        while (true) {
            //向右扫描
            while (i <= j && a[i] <= pivot)
                i++;
            //向左扫描
            while (i <= j && a[j] >= pivot)
                j--;
            if (i >= j)
                break;
            //交换
            int temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
        //把a[j]和主元交换
        a[left] = a[j];
        a[j] = pivot;
        return j;
    }

3. Because the worst time complexity of quicksort is O(n2). For example, there may be an extreme situation. In each division, the number of elements on the left of the pivot is 0, and the number of elements on the right is n-1. At this time, it needs to be divided n times. The time complexity of each segmentation is O(n), so the worst time complexity is O(n2). And the best case is that each partition can be divided from the middle of the array, so that it can be divided logn times, and the time complexity at this time is O(nlogn). The average time complexity assumes that each pivot will land at any position of the array with equal probability, and the final time complexity is O(nlogn). As for the specific calculation process, I will not expand it.

//随机选取主元的方法,为了降低极端情况出现的可能性,我们可以随机选取主元,而不是固定一个位置选取。
int random_partition(int[] arr, int left, int right)
{
 i = random(left, right);//随机选取一个位置
 //在把这个位置的元素与ar[left]交换
 swap(arr[i], arr[left]);
 
 return partition(arr, left, right);
}

Guess you like

Origin blog.csdn.net/weixin_41699562/article/details/104046268