如何使此QuickSort(用C语言编码)算法适应字符串数组?

问题描述 投票:0回答:2

我需要对内容进行排序(按字母顺序使用字符串数组的strcmp(),但是我不允许使用函数qsort()。通过此代码,我设法对数值进行了排序,但是我很难对其进行修改以对字符串进行排序。

/* A utility function to swap two elements */
void swap(int* a, int* b) 
{ 
    int t = *a; 
    *a = *b; 
    *b = t; 
} 

void swap_string(char c[63], char d[63]){
    char temp[63];
    strcpy(temp, c);
    strcpy(c, d);
    strcpy(d, temp);
}

/* This function takes last element as pivot, places 
   the pivot element at its correct position in sorted 
    array, and places all smaller (smaller than pivot) 
   to left of pivot and all greater elements to right 
   of pivot */
int partition (int arr[], int low, int high) 
{ 
    int pivot = arr[high];    /* pivot */
    int i = (low - 1);  /* Index of smaller element */

    for (j = low; j <= high- 1; j++) 
    { 
        /* If current element is smaller than the pivot */
        if (arr[j] < pivot) 
        { 
            i++;    /* increment index of smaller element */
            swap(&arr[i], &arr[j]); 
        } 
    } 
    swap(&arr[i + 1], &arr[high]); 
    return (i + 1); 
} 

/* The main function that implements QuickSort 
 arr[] --> Array to be sorted, 
  low  --> Starting index, 
  high  --> Ending index */
void quickSort(int arr[], int low, int high) 
{ 
    if (low < high) 
    { 
        /* pi is partitioning index, arr[p] is now 
           at right place */
        int pi = partition(arr, low, high); 

        /* Separately sort elements before */
        /* partition and after partition */
        quickSort(arr, low, pi - 1); 
        quickSort(arr, pi + 1, high); 
    } 
}

我需要对内容进行排序(按字母顺序使用字符串数组的strcmp(),但是我不允许使用函数qsort()。通过此代码,我设法对数值进行了排序,但是我有一个.. 。

c arrays string sorting quicksort
2个回答
0
投票

而不是使用整数数组(int arr []),请使用字符指针数组。希望这行得通!


0
投票

首先,您只需要为字符串创建交换函数,不需要int

© www.soinside.com 2019 - 2024. All rights reserved.