Thuật toán Quick - Sort (code)

#include <stdio.h>

int n = 10; // thay doi so luong phan tu o day
void printArray(int *a){
    for(int i=0;i<n;i++)
        printf("%2d ",a[i]);

}
void swap(int &a,int &b){
    int t = a;
    a = b;
    b = t;
}

int partition(int *a,int left,int right){
    int pivot = a[left];
    int i = left+1;
    int j = right ;
    do{
        while(i<=j && a[i]<=pivot)
            i++;
        while(i<=j && a[j]>pivot)
            j--;
        if (i<j){
            swap(a[i],a[j]);
            i++;
            j--;
        }

    }while (i<=j);
    swap(a[left],a[j]);
    return j;
}
void quickSort(int *a,int left,int right){
    if (left<right){
        int k = partition(a,left,right);
        quickSort(a,left,k-1);
        quickSort(a,k+1,right);

    }
}


int main(){
    // thay doi gia tri cua cac so de xem sap xep nhu the nao
    int *a =new int[n]{6,5,2,1,9,11,33,14,85,34};
    printArray(a);
    printf("\nMang sau khi sap xep:\n");
    quickSort(a,0,9);
    printArray(a);

    return 0;
}

Bài liên quan

Bài liên quan