Advertisement
Guest User

Untitled

a guest
Dec 5th, 2016
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.63 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. void quicksort(int arr[], int low, int high);
  4. void print_int_array(int arr[], int len);
  5.  
  6. int main(void){
  7.     int a[] = {6, 8, 3, 5, 9, 1, 2, 7, 4};
  8.     int len = sizeof(a) / sizeof(a[0]);
  9.  
  10.     print_int_array(a, len);
  11.  
  12.     quicksort(a, 0, len - 1);
  13.  
  14.     print_int_array(a, len);
  15.  
  16. }
  17.  
  18. void quicksort(int arr[], int low, int high){
  19.     // temp, i (left), j (right), pivot
  20.     int t, i, j, p;
  21.     if(low < high){
  22.         // set pivot to first element of the main array
  23.         p = low;
  24.  
  25.         // set "left" array's start to first element of the main array
  26.         i = low;
  27.  
  28.         // set "right" array's start to last element of the main array
  29.         j = high;
  30.  
  31.         // while the lowest index (which will increment) remains below the
  32.         // highest (which will decrement)
  33.         while(i < j){
  34.             // if the element in index i is smaller than the pivot,
  35.             // increase the lowest index
  36.             while(arr[i] <= arr[p] && i < high){
  37.                 i++;
  38.             }
  39.  
  40.             // if the element in index i is higher than the pivot, decrease
  41.             // the highest index
  42.             while(arr[j] > arr[p]){
  43.                 j--;
  44.                
  45.             }
  46.  
  47.             printf("i: %d\nj: %d\n", i, j);
  48.  
  49.             // if lowest index element remains lower than highest index element, swap them around
  50.             if(i < j){
  51.                 printf("swapping %d and %d\n", arr[i], arr[j]);
  52.                 t = arr[i];
  53.                 arr[i] = arr[j];
  54.                 arr[j] = t;
  55.             }
  56.         }
  57.  
  58.         // swap the pivot and the highest index???
  59.         t = arr[p];
  60.         arr[p] = arr[j];
  61.         arr[j] = t;
  62.  
  63.         quicksort(arr, low, j - 1); // sort left array
  64.         quicksort(arr, j + 1, high); // sort right array
  65.     }
  66.  
  67.  
  68. }
  69.  
  70. void print_int_array(int arr[], int len){
  71.     for(int i = 0; i < len; i++){
  72.         printf(" %d ", arr[i]);
  73.     }
  74.     printf("\n");
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement