E
E
een0t2020-12-11 19:38:12
C++ / C#
een0t, 2020-12-11 19:38:12

Why does it throw an Exception not handled when starting the program?

I wrote a program according to Hoare's algorithms, after entering the array size, the array itself is displayed, and then it gives an error: Unhandled exception at 0x007B2469 in Lab5, Task 5.4b.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x005E2F7C). and the sorted array is not output.

Here is the code itself, tell me where and what is the error?

spoiler
#include <cstdlib>
#include <Windows.h>
#include <iostream>
#include <ctime>

using namespace std;

void arr_sort(int* arr, int first, int last)
{
  int mid, dop;
  int f = first, l = last;
  mid = arr[(f + 1) / 2];
  do
  {
    while (arr[f] < mid) f++;
    while (arr[l] > mid) l--;
    if (f <= l)
    {
      dop = arr[f];
      arr[f] = arr[l];
      arr[l] = dop;
      f++;
      l--;
    }
  } while (f < l);
  if (first < l) arr_sort(arr, first, l);
  if (f < last) arr_sort(arr, f, last);
}

int main()
{
  SetConsoleCP(1251);
  SetConsoleOutputCP(1251);
  int n;
  cout << "Введите размер массива: "; cin >> n;
  int* arr = new int[n];
  for (int i = 0; i<int(n); i++)
    arr[i] = rand() % 200 - 100;
  cout << "Исходный массив: ";
  for (int i = 0; i<int(n); i++)
    cout << arr[i] << " ";
  cout << "\n";
  cout << " Отсортированный массив: ";
  arr_sort(arr, 0, n - 1);
  for (int i = 0; i < n; i++) {
    cout << arr[i] << " ";
  }
  cout << "\n";
  system("PAUSE");
  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2020-12-11
@een0t

This means that you messed up with recursion somewhere and arr_sort is called until a stack overflow occurs.
Well, since you do not use any exception handler, the exception is not handled anywhere.
PS And if you do not understand the essence of the algorithm, then you need to reprint it more carefully. Here there should be not a unit, but l.
mid = arr[(f + l) / 2];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question