I can not understand this algorithm in any way, Can someone explain to me in stages ... I would be grateful

searchKey=55; for(j=0;j<nElems;j++){ // Поиск удаляемого элемента if(arr[j]==searchKey){ break; } } for(int k = j;k<nElems-1;k++){ // Сдвиг последующих элементов arr[k] = arr[k+1]; } nElems--; // Уменьшение размера 

The algorithm is implemented from the book.

  • 3
    Brad happens here. An array is needed when the data is static. If they are dynamic, then use ArrayList , which automatically updates the size and cleans holes when inserting, deleting, etc. - Flippy
  • @Flippy clearly however) - elik
  • one
    It looks like a code ported from C - Barmaley
  • @Barmaley yes it is from the book for algorithms ...) - elik
  • one
    A hike is a bad book, in C you have to do differently - on pointers, I’m on Java, too, completely different - Barmaley

2 answers 2

  • above, the variable j , which will contain the index of the desired element in the array
  • the first loop goes through the array at each iteration, the value is checked for what it is looking for, if so, then exit the loop with break
  • after this cycle, the variable j contains the index of the desired value in the array
  • then the second cycle shifts the elements to the left starting from the index j
  • the last element of the array becomes "removed", in fact, it is, just cycles will not pay attention to it, since the variable nElrms has decreased

    In a nutshell

    This piece of code "cuts out" from the input sequence the first element with the value of searchKey


    And now more:

    searchKey - the desired value in the sequence
    for(j=0;j<nElems;j++) - pass through the sequence from 0 to nElems (most likely it is the length of the sequence)
    if(arr[j]==searchKey) { break; } if(arr[j]==searchKey) { break; } - if the j-th element of the sequence arr is equal to searchKey (in this case 55), then break (stop the cycle, while j = the index of the element with the value searchkey

     for(int k = j;k<nElems-1;k++){ arr[k] = arr[k+1]; } 

    Passing through the same sequence, only now not from the beginning to the end, but from j to nElems - 1 and the current elements of the sequence are assigned the value of the following (in other words, we cut the element with the value of searchKey )
    nElems-- - reduce the length of the sequence by one.


    But, frankly, I absolutely agree with the speaker in the comments. You use an array and "cut out" the value from it, but, to be honest, cutting cannot be called cutting. Since you substitute the remaining elements of the array instead, but this does not change its size, it both consisted of n elements and consists of.