Signup/Sign In

Quick Sort Program In C Language

learn C language tutorial

Quick Sort:

  • The Quick Sort is a type of sorting algorithm, It works on the basis of the divide and conquers method,
  • The given array is divided into sub-arrays by selecting an element from the array,
  • From the unsorted array, the values less than the selected values are kept on the left side, greater values are kept on the right side,
  • The subarrays are also divided in the same way, the division process will continue until there is only one element left in the array,
  • At this stage, the elements will be sorted and combined into a sorted array.
  • You can learn more about Quick Sort Algorithm from here

C Language Program For Quick Sort Using C:

// Quicksort Using C Program

#include <stdio.h>

// Swap Function
void swap(int *n1, int *n2) {
  int m = *n1;
  *n1 = *n2;
  *n2 = m;
}

int partition(int arr[], int x, int y) {
  
  int pivot = arr[y];
  
  int i = (x - 1);

  for (int j = x; j < y; j++) {
    if (arr[j] <= pivot) {
        
      i++;
      
      swap(&arr[i], &arr[j]);
    }
  }

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

void quickSort(int arr[], int x, int y) {
  if (x < y) {
    
    int pi = partition(arr, x, y);
    
    quickSort(arr, x, pi - 1);
    
    quickSort(arr, pi + 1, y);
  }
}

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

int main() {
  int values[] = {99, 88, 64, 25, 40, 20, 42};
  
  int n = sizeof(values) / sizeof(values[0]);
  
  printf("Given Unsorted Array Values \n");
  printArray(values, n);
  
  quickSort(values, 0, n - 1);
  
  printf("Sorting Given Array In The Ascending Order: \n");
  printArray(values, n);
}

Output:

Quick