예제 #1
0
void doQuickSort(int **array, const int kFirst, const int kLast)
{
    if (kFirst >= kLast)
        return;

    int i = kFirst;
    int j = kLast;
    int pivot = (*array)[j];

    while (i < j) {
        while (i < j && (*array)[i] < pivot)
            ++i;
        if (i < j)
            (*array)[j--] = (*array)[i];
        while (i < j && (*array)[j] > pivot)
            --j;
        if (i < j)
            (*array)[i++] = (*array)[j];
    }

    (*array)[i] = pivot;

    if (kFirst < i - 1)
        doQuickSort(array, kFirst, i - 1);
    if (i + 1 < kLast)
        doQuickSort(array, i + 1, kLast);
}
예제 #2
0
void doQuickSort(T arr[], int start, int end) {
    if (start >= end)
        return;

    //Partition operation
    T pivotValue = arr[end];
    int pivotIndex = start;

    for (int i = start; i < end; i++) {
        if (arr[i] < pivotValue) {
            T temp = arr[pivotIndex];
            arr[pivotIndex++] = arr[i];
            arr[i] = temp;
        }
    }

    T temp = arr[pivotIndex];
    arr[pivotIndex] = arr[end];
    arr[end] = temp;

    //Recursive call
    doQuickSort(arr, start, pivotIndex - 1);
    doQuickSort(arr, pivotIndex + 1, end);
}
예제 #3
0
int main(void)
{
    int i;
    int n;
    int *array;

    puts("Please enter n:");
    scanf("%d", &n);

    if (n < 1) {
        puts("Input Error");
        return 1;
    }
    else if (n == 1) {
        puts("Now please enter 1 number:");
    }
    else {
        printf("Now please enter %d numbers:\n", n);
    }
    array = (int *)malloc(sizeof(int) * (size_t)(n));
    assert(array != NULL);
    for (i = 0; i < n; ++i)
        scanf("%d", array + i);

    puts("\nNow sort the array.\n\nHere is the result:");

    doQuickSort(&array, 0, n - 1);

    for (i = 0; i < n; ++i)
        printf("%d ", array[i]);
    putchar('\n');

    free(array);

    return 0;
}
예제 #4
0
void quickSort(T arr[], int size) {
    doQuickSort(arr, 0, size - 1);
}