Home > Enterprise >  Using QuickSort Ascending and Descending in C language
Using QuickSort Ascending and Descending in C language

Time:09-30

The Ascending worked fine but the Descending doesn't. The outcome of the Sorted Descending isn't right...

This is the execution:

Unsorted Array: 20 10 5 27 0 3 15

Ascending Sorted Array: 0 3 5 10 15 20 27
Descending Sorted Array: 27 0 3 5 10 15 20

What seems to be the problem of my code?

#include <stdio.h>

#define size 7


void quickAscending(int array[size], int start, int end){
    
    int temp;
    
    if(start < end){
        
    int pointer = start;
    int pivot = array[end];
    int count;
    
    for(count = start; count < end; count  )
    {
        if(array[count] < pivot) //ari change
        {
            temp = array[count];
            array[count] = array[pointer];
            array[pointer] = temp;
            
            pointer  ;
        }
    }
    
    temp = array[end];
    array[end] = array[pointer];
    array[pointer] = temp;
    
    quickAscending(array, start, pointer-1);
    quickAscending(array, pointer 1, end);
    
    }

}

void quickDescending(int array[size], int start, int end){
    
int temp;
    
    if(start < end){
        
    int pointer = start;
    int pivot = array[end];
    int count;
    
    for(count = start; count < end; count  )
    {
        if(array[count] > pivot) 
        {
            temp = array[count];
            array[count] = array[pointer];
            array[pointer] = temp;
            
            pointer  ;
        }
    }
    
    temp = array[end];
    array[end] = array[pointer];
    array[pointer] = temp;
    
    quickAscending(array, start, pointer-1);
    quickAscending(array, pointer 1, end);
    
    }

}

void displayArray(int array[size]){
    
    int count; 
    
    for(count = 0; count < size; count  ){
    printf("%d ", array[count]);
    }

}

int main(){

  int array[size] = {20, 10, 5, 27, 0, 3, 15};

  printf("Unsorted Array: ");
  displayArray(array);

  quickAscending(array, 0, size - 1);
  printf("\n\nAscending Sorted Array: ");
  displayArray(array);
  
  quickDescending(array, 0, size - 1);
  printf("\nDescending Sorted Array: ");
  displayArray(array);
  
}

I did my best to analyze where I might go wrong but my brain isn't working anymore :(

CodePudding user response:

Looks like the problem is with copy-pasting your code. You need to call quickDescending instead of quickAscending inside quickDescending function.

void quickDescending(int array[size], int start, int end){

int temp;
    ...
    ...
    temp = array[end];
    array[end] = array[pointer];
    array[pointer] = temp;
    
    quickDescending(array, start, pointer-1);//Changed to quickDescending
    quickDescending(array, pointer 1, end);//Changed to quickDescending
    
    }

}

void displayArray(int array[size]){
  • Related