Advertisement
darkjessy94

quicksort

Sep 7th, 2017
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. // quickSort.c
  2. #include <stdio.h>
  3.  
  4. void quickSort( int[], int, int);
  5. int partition( int[], int, int);
  6.  
  7.  
  8. void main()
  9. {
  10. int a[] = { 7, 12, 1, -2, 0, 15, 4, 11, 9};
  11.  
  12. int i;
  13. printf("\n\nUnsorted array is: ");
  14. for(i = 0; i < 9; ++i)
  15. printf(" %d ", a[i]);
  16.  
  17. quickSort( a, 0, 8);
  18.  
  19. printf("\n\nSorted array is: ");
  20. for(i = 0; i < 9; ++i)
  21. printf(" %d ", a[i]);
  22.  
  23. }
  24.  
  25.  
  26.  
  27. void quickSort( int a[], int inizio, int fine)
  28. {
  29. int i_partiz;
  30. printf("\ninizio= %d",inizio);
  31.  
  32. if( inizio < fine )
  33. {
  34. // divide and conquer
  35. i_partiz = partition( a, inizio, fine);
  36. quickSort( a, inizio, i_partiz-1);
  37. quickSort( a, i_partiz+1, fine);
  38. }
  39.  
  40. }
  41.  
  42.  
  43.  
  44. void swap(int* a, int* b)
  45. {
  46. int t = *a;
  47. *a = *b;
  48. *b = t;
  49. }
  50.  
  51. int partition (int arr[], int low, int high)
  52. {
  53. int pivot = arr[high]; // pivot
  54. int i = (low - 1); ///il muro
  55. int j;///l'elem minore
  56. for (j = low; j < high; j++)
  57. {
  58. if (arr[j] < pivot)
  59. {
  60. i++; ///il muro si incrementa
  61. swap(&arr[i], &arr[j]); ///scambia il muro con l'elem attuale
  62. }
  63. }
  64. swap(&arr[i + 1], &arr[high]);
  65. return (i+1);
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement