Page 242 - DCAP201_FUNDAMENTALS_OF_DATA_STRUCTURES
P. 242

Unit 13: Sorting




                  int aux;                                                                      Notes
                  aux = a;
                  a = b;
                  b = aux;
          }
          int partition (int *a, int low, int high)
          {
                  int l = low;
                  int h = high;
                  int x = a[l];
                  while (l < h)
                  {
                          while ((a[l] <= x) && (l <= high))
                                  l++;
                          while ((a[h] > x) && (h >= low))
                                  h—;
                          if (l < h)
                                  swap(a[l], a[h]);
                  }
                  swap (a[low], a[h]);
                  return h;
          }


          void QuickSort (int *a, int low, int high)
          {
                  int k;
                  if (high > low)
                  {
                          k = partition(a, low, high);
                          QuickSort (a, low, k-1);
                          QuickSort (a, k+1, high);
                  }
          }
          int main()
          {
                  int n;
                  int *a;
                  cout << “Please insert the number of elements to be sorted:”;
                  cin >> n;       // The total number of elements
                  a = (int *)calloc(n, sizeof(int));
                  for(int i=0; i<n; i++)
                  {




                                           LOVELY PROFESSIONAL UNIVERSITY                                   235
   237   238   239   240   241   242   243   244   245   246   247