Advertisement
cd62131

Quick Sort

Dec 6th, 2013
605
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.02 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. void printData(double *Data, int L, int R) {
  5.   for (int i = L; i <= R ; i++) {
  6.     printf("%g ", Data[i]);
  7.   }
  8.   printf("\n");
  9. }
  10.  
  11. void swap(double *x, double *y) {
  12.   double swap = *x;
  13.   *x = *y;
  14.   *y = swap;
  15. }
  16.  
  17. void quickSortBase(double *Data, int L, int R) {
  18.   int pivot_index = (L + R) / 2;
  19.   double pivot = Data[pivot_index];
  20.   printf("sorting [%d] ... [%d], pivot=[%d]:%g\n", L, R, pivot_index, pivot);
  21.   int i = L;
  22.   int j = R;
  23.   while (1) {
  24.     while (Data[i] < pivot) i++;
  25.     while (pivot < Data[j]) j--;
  26.     if (i >= j) break;
  27.     printf("swapped [%d]:%g <=> [%d]:%g\n", i, Data[i], j, Data[j]);
  28.     swap(&Data[i], &Data[j]);
  29.     i++;
  30.     j--;
  31.   }
  32.   quickSortBase(Data, L, i - 1);
  33.   quickSortBase(Data, j + 1, R);
  34. }
  35.  
  36. void quickSort(double *Data, int N) {
  37.   if (N >= 2) {
  38.     quickSortBase(Data, 0, N);
  39.   }
  40. }
  41.  
  42. int main(void) {
  43.   double Data[] = { 1., 3., 4., 3., 5., 5., 2., 4. };
  44.   int N = sizeof(Data) / sizeof(Data[0]);
  45.   quickSort(Data, N);
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement