Personal understanding of the recursive implementation of the quicksort algorithm

Personal understanding of the recursive implementation of the quicksort algorithm


    Regarding quick sort, the algorithm realizes the principle is to divide a set of data to be sorted according to a selected data, and divide the data into two sides with this data as the center, one side is large and the other is small, and recursion is used to divide the two groups of data. Re-grouping is carried out separately until it can no longer be divided, and the sorting is completed at this time.
    Therefore, the center of the quick sort algorithm should be how to divide the data into two groups according to the selected data , and here the selected data is directly defaulted to the first data of the data group , although it may be slow in some cases, but in most cases is faster than the general sorting algorithm.
    The C++ implementation of quick sort is as follows (here is the ascending sort method):

void quick_sort(array<int,19> arr,int start,int end){
    if(start<end){//递归结束条件
        int first = start;
        int last = end;
        int flag = arr[start];
        while(first<last){
//start和end为函数传进来的数组的头和尾,使用两个变量保存
        int first = start;
        int last = end;
//保存被选中的数,这里直接使用第一个元素,也可以通过计算出头,尾,中间三个值,取出中值与第一个元素交换位置,确保最坏情况不会发生
        int flag = arr[start];
        while(first<last){//使用循环,确保在头尾碰头之前遍历完所有数据
            while(first<last&&arr[last]>=flag){
                --last;
            }
            //从尾部开始遍历查找比被选中的数小的数,并将它放在头的位置
            arr[first]=arr[last];
            while(first<last&&arr[first]<=flag){
                ++first;
            }
            //接着从头部开始遍历查找比被选择的数大的数,并将它放在尾的位置
            arr[last]=arr[first];
        }//如果头尾没有碰头,则继续进行比较,确保以被选中的数为界的左右两侧数据组一大一小
        arr[first]=flag;//将被选中的数放在两组数据的中间
        //使用递归再次排序
        quick_sort(arr,start,first-1);
        quick_sort(arr,first+1,end); 
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325386263&siteId=291194637