There are different ways to implement a quick sort algorithm in C. Here is an example of a quick sort algorithm that sorts an array of two elements:

#include <stdio.h>

void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int partition(int arr[], int low, int high) {
    int pivot = arr[high];
    int i = (low - 1);

    for (int j = low; j <= high - 1; j++) {
        if (arr[j] < pivot) {
            i++;
            swap(&arr[i], &arr[j]);
        }
    }

    swap(&arr[i + 1], &arr[high]);
    return (i + 1);
}

void quickSort(int arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);

        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf('%d ', arr[i]);
    }
    printf('
');
}

int main() {
    int arr[] = {2, 1};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf('Original array: ');
    printArray(arr, n);

    quickSort(arr, 0, n - 1);

    printf('Sorted array: ');
    printArray(arr, n);

    return 0;
}

In this code, the 'swap()' function is used to swap two elements in the array. The 'partition()' function selects the last element as the pivot and rearranges the array such that all elements smaller than the pivot are placed before it, and all elements greater than the pivot are placed after it. The 'quickSort()' function recursively calls itself to sort the left and right sub-arrays. Finally, the 'printArray()' function is used to print the sorted array.


原文地址: https://www.cveoy.top/t/topic/NYx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录