Advertisement
Shailrshah

Quick Sort

Sep 23rd, 2013
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.92 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. void swap (int *x, int *y){
  4.     if (x != y){
  5.         *x += *y; *y = *x - *y; *x -= *y;
  6.     }
  7.  }
  8. int partition(int a[], int start, int end){
  9.     int pivotIndex = (start+end)/2; //can be anything between start and end.
  10.     int pivotValue = a[pivotIndex], i = start - 1;
  11.     swap(&a[pivotIndex], &a[end]);
  12.     for(int j = start; j != end; j++)
  13.         if(a[j] <= pivotValue) swap(&a[++i], &a[j]);
  14.     swap(&a[i+1], &a[end]);
  15.     return i+1;
  16. }
  17. void quickSort(int a[], int start, int end){
  18.     if(start < end){
  19.         int q = partition(a, start, end);
  20.         quickSort(a, start, q - 1);
  21.         quickSort(a, q + 1, end);
  22.     }
  23. }
  24. int main(){
  25.     int *a, i, n;
  26.     printf("Enter the number of elements: ");
  27.     scanf("%d", &n);
  28.     a = (int *) malloc(sizeof(int) * n);
  29.     for(i = 0; i < n; i++) scanf("%d", &a[i]);
  30.     quickSort(a, 0, n-1);
  31.     for(i = 0; i < n; i++) printf("\t%d\t", a[i]);
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement