You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在GCC环境下用C语言实现指定基准值的快速排序需求

完整实现指定基准的快速排序(GCC环境)

针对你提出的需求——对数组{2,3,11,9,12,2,6,15,18,10,7,14}执行快速排序,指定索引11处的元素14作为基准值,我已经补全了C语言代码的完整实现,完全兼容GCC编译环境:

#include <stdio.h>
#include <stdlib.h>
#define DATA_SIZE 12
void quick_sort(int *list, int left, int right);
int partition(int *list, int left, int right);
void SWAP(int *x, int *y, int *t) { *t = *x; *x = *y; *y = *t; }

/*main start*/
int main() {
    // Initialize data[] for sorting
    int data[DATA_SIZE] = {2,3,11,9,12,2,6,15,18,10,7,14};
    int i;

    printf("Original array: ");
    for(i = 0; i < DATA_SIZE; i++) {
        printf("%d ", data[i]);
    }
    printf("\n");

    // Call quick_sort, start with entire array (left=0, right=DATA_SIZE-1=11)
    quick_sort(data, 0, DATA_SIZE - 1);

    printf("Sorted array:   ");
    for(i = 0; i < DATA_SIZE; i++) {
        printf("%d ", data[i]);
    }
    printf("\n");

    return 0;
}

/* Quick sort recursive implementation */
void quick_sort(int *list, int left, int right) {
    int pivot_pos;
    if(left < right) {
        // Partition the array and get pivot's final position
        pivot_pos = partition(list, left, right);
        // Recursively sort left subarray
        quick_sort(list, left, pivot_pos - 1);
        // Recursively sort right subarray
        quick_sort(list, pivot_pos + 1, right);
    }
}

/* Partition function with pivot at rightmost element (index 11 initially) */
int partition(int *list, int left, int right) {
    int pivot = list[right]; // Use the specified pivot (index 11 element:14)
    int i = left - 1; // Index of smaller element
    int temp; // Temporary variable for SWAP

    for(int j = left; j <= right - 1; j++) {
        // If current element is <= pivot
        if(list[j] <= pivot) {
            i++; // Increment index of smaller element
            SWAP(&list[i], &list[j], &temp);
        }
    }
    // Place pivot in its correct position
    SWAP(&list[i + 1], &list[right], &temp);
    return (i + 1);
}

关键细节说明:

  • 基准值处理:按照你的要求,我们直接取list[right]作为基准(首次调用时right=11,对应元素14),完全符合指定需求。
  • SWAP函数适配:严格使用你提供的三参数SWAP函数,通过临时变量temp完成元素交换。
  • 递归逻辑:quick_sort函数通过递归划分左右子数组,直到子数组长度为1(left >= right)时终止。
  • GCC兼容性:代码使用标准C语法,无GCC专属特性,直接用gcc quicksort.c -o quicksort编译即可运行。

运行输出示例:

Original array: 2 3 11 9 12 2 6 15 18 10 7 14 
Sorted array:   2 2 3 6 7 9 10 11 12 14 15 18 

内容的提问来源于stack exchange,提问作者robin eu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 02:29:04