N
N
NikitkOS2018-05-17 12:00:40
C++ / C#
NikitkOS, 2018-05-17 12:00:40

How to fix an array being filled with the minimum values ​​of another array?

The essence of the program is as follows: you need to write to the array minimumArray five minimum elements of the array yourArray, while adding to the busyI array the i values ​​​​from the loop that have already been used, and when checking, go to the next value i when calling the function from main.
The program works correctly, but if the zero element of the array yourArray is one of the five minimum elements, then i = 0 is cyclically added to busyI, and I don't really understand why. Is it possible to somehow fix this "miracle" code of mine?
PS I know that you can do it all much easier - through the same sorting, but I wanted to do this, so please do not completely rewrite the entire code using some other method, but point out the errors that need to be fixed.

const int lengthArr = 10, lengthArr2 = 5;
int yourArray[lengthArr], minimumArray[lengthArr2], busyI[lengthArr2] = {-1, -1, -1, -1, -1};
static int arrTwo = 0;

//функция заполнения массива yourArray рандомными числами 

void writeMinimum(int arr[], int arrI[]) {
  int minI = 0, min1 = arr[minI], breakVar = -1;
  for (int i = 0; i < lengthArr; i++) {
    for (int k = 0; k < arrTwo; k++) {
      if (i == arrI[k]) {
        breakVar = i;
        break;
      }
    }
    if (breakVar == 0) {
      break;
    }else if ((arr[i] < min1) && (i != breakVar)) {
      min1 = arr[i];
      minI = i;
    }
  }
  arrI[arrTwo] = minI;
  minimumArray[arrTwo] = min1;
  arrTwo++;
}

int main()
{
       // Вызов функции заполнения массива
  for(int i = 0; i < lengthArr2; i++){
  writeMinimum(yourArray, busyI);
  }
  system("pause");
  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2018-05-17
@NikitkOS

When you find the minimum element in the original array, save its value and index, replace the value of the minimum element in the original array with some maximum possible number (INT_MAX in your case). Repeat the procedure until the entire array of minima is filled.
Then you need to restore the original array using the previously saved information.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question