排序——快排算法实现

今天在牛客网看了一些排序的原理,然后就编了一个快速排序的算法,并且测试通过。下面我来讲基本思想,主要是参考做老师的思路,自己实现出来。

快排思想:在数组中随机选择一个数作为参考,比该数大的放在它的右边,比它小的放在它的左边。之后把它的左右两边看成另外两个新数组(不包括该数)进行递归。在实际进行快速排序的算法编写时我们一般选数组的第一个数作为参考元素来比较进行快排。

实现思想:前提数组第一个元素为比较的值key,然后数组 A 首元素和尾元素调换,在对调换后数组的前n-1(n为传进来数组的长度)个元素进行遍历;并用count进行计数(count的作用是作为两个子数组的分割),count初值为left;遍历时若元素大于等于key(等于放哪都无所谓),进行下一次循环;若小于key则调换A[i]和A[count],并且count + 1;遍历完成之后调换A[right]和A[count],并把 (A, left, count - 1)和(A, count + 1, right)两个子数组调用递归

基本过程  4 1 5 8 3 ->3 1 5 8 4 -> {3}1 5 8 4 ->{3 1} 5 8 4 ->{3 1} 4 8 5->{3 1} 4 {8 5}

上述变化完之后count处的值就是key的值,count左右的值分别为小于和大于key的值。

重点代码

    void qSort(int* A,int left,int right){   
    if (left < right){
        int count = left;
        int key = A[left];
        swap(A[left], A[right]);
        for (int i = left; i < right ; ++i){
            if (A[i] >= key)
                continue;
            else {
                swap(A[count], A[i]);
                count++;
            }
        }
        swap(A[count], A[right]);
        qSort(A, left, count - 1);
        qSort(A, count + 1, right);
    }
}

该算法时间复杂度为O(n),比较实惠。

最后贴上自己实现的一段完整代码:

#include<iostream>
using namespace std;
//快排理论:在数组中随机选择一个数,比该数大的放在它的右边,比它小的放在它的左边。之后把它的左右两边看成另外两个新数组(不包括该数)进行递归。
//在实际中我们一般选数组的第一个数来比较进行快排。
void swap(int &a, int &b){
    int temp = a;
    a = b;
    b = temp;
}

//实现思想:前提数组第一个元素为比较的值key
//数组 A 首元素和尾元素调换,在对该数组的前n-1(n为传进来数组的长度)个元素进行遍历;并用count进行计数,count初值为left;
//遍历时若元素大于等于key(等于放哪都无所谓),进行下一次循环;若小于key则调换A[i]和A[count],并且count + 1(count是用来进行分割数组的);
//遍历完成之后调换A[right]和A[count],并把 (A, left, count - 1)和(A, count + 1, right)两个子数组调用递归

void qSort(int* A,int left,int right){   
    if (left < right){
        int count = left;
        int key = A[left];
        swap(A[left], A[right]);
        for (int i = left; i < right ; ++i){
            if (A[i] >= key)
                continue;
            else {
                swap(A[count], A[i]);
                count++;
            }
        }
        swap(A[count], A[right]);
        qSort(A, left, count - 1);
        qSort(A, count + 1, right);
    }
}
int* quickSort(int* A, int n) {
    if (A == NULL)
        return NULL;
    qSort(A, 0, n - 1);
    return A;
}
int main(){
    const int n = 9;
    int a[n] = { 7, 6, 9, 8, 2, 5, 4, 3, 1 };//任意的例子
    for (int i = 0; i != n; ++i){
        cout << a[i] << " ";
    }
    cout << endl;
    quickSort(a, n);
    for (int i = 0; i != n; ++i){
        cout << a[i] << " ";
    }
    cout << endl;
    return 0;
}

 

原文地址:https://www.cnblogs.com/jlxuexijidi-2015/p/4890500.html