Answer to Question #273269 in C for Amit

Question #273269

Implement quick sort. 


1
Expert's answer
2021-11-30T00:36:56-0500

Source code

#include <stdio.h>
void swap(int *x, int *y) {
  int temp = *x;
  *x = *y;
  *y = temp;
}
int partition(int arr[], int l, int h) {
  int pvt = arr[h];
  int i = (l - 1);
  for (int j = l; j < h; j++) {
    if (arr[j] <= pvt) {
      i++;
      swap(&arr[i], &arr[j]);
    }
  }


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


void qiuck_sort(int arr[], int l, int h) {
  if (l < h) {
    int p = partition(arr, l, h);
    qiuck_sort(arr, l, p - 1);
    qiuck_sort(arr, p + 1, h);
  }
}


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


int main() {
  int arr[] = {15,12,17,16,11,20,18,12,19,13,14};
  
  int size = sizeof(arr) / sizeof(arr[0]);
  
  printf("Array elements before sorting: \n");
  display(arr, size);
  qiuck_sort(arr, 0, size - 1);
  
  printf("Array elements after sorting in ascending order: \n");
  display(arr, size);
}


Output





Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS