java - How does this delete an element from an array? -
i using book data structures , algorithms in java learn (you guessed it) - data structures , algorithms. piece of code confuses me. have tested , works don't see in code specify delete 55 exactly?
i see search in array , move data elements index don't see tell compiler delete 55.
searchkey = 55; // delete item key 55 for(j=0; j<nelems; j++) // if(arr[j] == searchkey) break; for(int k=j; k<nelems-1; k++) // move higher ones down arr[k] = arr[k+1]; nelems--; // decrement size
to precise, code not delete array element; overrides it.
note how j
declared outside first loop, , used in second loop initialize value of k
. first loop walks j
through array, until j
"points" element value of 55
. when happens, code exits loop through break
, when second loop reads j
, still points location in array 55
stored. second loop copies elements k+1
-st location k
-th, "overriding" value of 55
on first iteration, , moving rest of values in consecutive iterations.
consider example:
index: 0 1 2 3 4 5 value: 30 40 55 60 70 80
after first loop j
set 2
. each iteration of second loop changes array follows:
index: 0 1 2 3 4 5 iteration 0: 30 40 55 60 70 80 iteration 1: 30 40 60 60 70 80 iteration 2: 30 40 60 70 70 80 iteration 3: 30 40 60 70 80 80
at point nelems
decremented, making sure last element (i.e. 80
) disregarded if program runs again.
Comments
Post a Comment