0
const int RUN = 32;
void insertionSort(int arr[], int left, int right)
{
    for (int i = left + 1; i <= right; i++)
    {
        int temp = arr[i];
        int j = i - 1;
        while (j >= left && arr[j] > temp)
        {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = temp;
    }
}
void merge(int arr[], int l, int m, int r)
{
  // original array is broken in two parts
  // left and right array
  int len1 = m - l + 1, len2 = r - m;
  int left[len1], right[len2];
  for (int i = 0; i < len1; i++)
    left[i] = arr[l + i];
  for (int i = 0; i < len2; i++)
    right[i] = arr[m + 1 + i];

  int i = 0;
  int j = 0;
  int k = l;


  // after comparing, we merge those two array
  // in larger sub array
  while (i < len1 && j < len2)
  {
    if (left[i] <= right[j])
    {
        arr[k] = left[i];
        i++;
    }
    else
    {
        arr[k] = right[j];
        j++;
    }
    k++;
  }

  // copy remaining elements of left, if any
  while (i < len1)
  {
    arr[k] = left[i];
    k++;
    i++;
  }

  // copy remaining element of right, if any
  while (j < len2)
  {
    arr[k] = right[j];
    k++;
    j++;
  }
}
void timSort(int arr[], int n) {
    for (int i = 0; i < n; i += RUN)
        insertionSort(arr, i, min((i + RUN - 1), (n - 1)));
    for (int size = RUN; size < n; size = 2 * size) {
        for (int l = 0; l < n; l += 2 * size) {
            int m = l + size - 1;
            int r = min((l + 2 * size - 1), (n - 1));
            if (m < r)
                merge(arr, l,m,r);
        }
    }
}

int main()
{
    int arr[] = { 40,39,38,37,36,35,34,33,32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << n << endl;
    cout << "Array :" << endl;
    for (int i = 0; i < n; i++) {
        cout << setw(3) << arr[i];
    }
    timSort(arr, n);
    cout << "\nAfter Timsort: " << endl;
    for (int i = 0; i < n; i++) {
        cout << setw(3) << arr[i];
    }
    return 0;
}

Here I have an issue

I am still a beginner in C++ programming and the code above is combined using various sources online. Please assist me in identifying the issue!

The program is a standard implementation of timsort, efficiently combining arrays sorted using insertion sort.

It says that expression must be constant. I found this code in Internet, and everything worked there, but it doesn't work for me.

SOLUTION:

I changed this int left[len1], right[len2]; to this std::vector<int> left;std::vector<int> right; and after it I wrote left.resize(len1); right.resize(len2);

  • 2
    Do NOT post code as images. `int left[len1], right[len2];` is not valid C++, arrays must have compile-time bounds. use `std::vector` if the size is dynamic. – Quimby Nov 21 '21 at 17:33
  • You need to give an example of how you are using this function so that we can reproduce the problem. – Wais Kamal Nov 21 '21 at 17:35

0 Answers0