Exemple #1
0
static void myQsort(const char *array[],size_t num){
    const char *temp;
    size_t i,j;
    if(num < 2)
        return;
    else if(num == 2){
        if(strcmp(array[0], array[1]) > 0)
                exchange(array[0], array[1],temp);
    }
    //partition the array using the middle(num/2)
    //element as the dividing element
    exchange(array[0],array[num/2],temp);
    i = 1;
    j = num;
    for(;;){
      //sweep forward until an element is found
      //that belongs  in the second partition
      while (i < j && strcmp(array[i],array[0]) <= 0)
        i++;
        //Then sweep backward until an element
        //is found that belongs in the first
        //partition
        while(i < j && strcmp(array[j-1],array[0]) >= 0)
          j--;
          //if no out-of-place elements, youre done
          if(i >= j)
            break;
          exchange(array[i], array[j-1], temp);
    }
    //restore dividing element
    exchange(array[0],array[i-1],temp);
    //now apply quick sort to each partition
    myQsort(array, i - 1);
    myQsort(array + i, num - 1);
}
Exemple #2
0
int main(int argc,char **argv){
    char *arr[]={"bob","zeynab","alice","john"};
    myQsort(arr,sizeof(arr)/sizeof(arr[0]));
    displayarray(arr, sizeof(arr)/sizeof(arr[0]));
    return 0;

}
void testNumbers(void){
    
    FILE *input;
    FILE *output;
    void *array;
    int numElmnts;

    void *testArray;
    int *testnArray;
    int i;

    input = fopen(TEST_FILE_INPUT, "r");
    if(input == NULL){
	printf("Could not open file\n");
	exit(1);
    }

    numElmnts = numbersGetAmount(input);
    array = malloc(numElmnts * NUMBERS_SIZE);

    numbersFillArray(input, numElmnts, array);
    fclose(input);

    myQsort(array, numElmnts, NUMBERS_SIZE, numbersCmp);

    output = fopen(TEST_FILE_OUTPUT, "w");
    if(output == NULL){
	printf("Could not open file\n");
	exit(1);
    }

    numbersWrite(output, numElmnts, array);

    fclose(output);
    free(array);

    //Confirm the output is valid!
    testArray = malloc(numElmnts * NUMBERS_SIZE);
    testnArray = testArray;

    input = fopen(TEST_FILE_OUTPUT, "r");
    if(input == NULL){
	printf("Could not open file\n");
	exit(1);
    }

    numbersFillArray(input, numElmnts, testArray);
    fclose(input);

    for(i = 0; i < numElmnts - 1; i++){
	g_assert(testnArray[i] <= testnArray[i + 1]);
    }
    free(testArray);
}