java - Deleting an item from array -
class arrayapp{ public static void main(final string[] args){ long[] arr; // reference array arr = new long[100]; // make array int nelems = 0; // number of items int j; // loop counter long searchkey; // key of item search // -------------------------------------------------------------- arr[0] = 77; // insert 10 items arr[1] = 99; arr[2] = 44; arr[3] = 55; arr[4] = 22; arr[5] = 88; arr[6] = 11; arr[7] = 00; arr[8] = 66; arr[9] = 33; nelems = 10; // 10 items in array // -------------------------------------------------------------- for(j = 0; j < nelems; j++){ system.out.print(arr[j] + " "); } system.out.println(""); // -------------------------------------------------------------- searchkey = 66; // find item key 66 for(j = 0; j < nelems; j++){ if(arr[j] == searchkey){ break; // yes, exit before end } } if(j == nelems){ system.out.println("can’t find " + searchkey); // yes } else{ system.out.println("found " + searchkey); // no } // -------------------------------------------------------------- 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++){ arr[k] = arr[k + 1]; } nelems--; // decrement size // -------------------------------------------------------------- for(j = 0; j < nelems; j++){ system.out.print(arr[j] + " "); } system.out.println(""); } // end main() } // end class arrayapp
- why use j , nelems search array.
- why again assign j k deletion? can't delete j itself?
nelemens used speed search. in example above array has 100 fields. need search 100 fields. since nelemen (the number of elements) 10, necessary search 10 elements instead of 100.
but careful: algorithm above assumes array filled in correct order , there can't gaps between fields have value.
then variable j used loop variable access different fields in array.
e.g.
arr[5] accesses 6. field of array. arr[j] accesses j. element in array. basic information java loops:
Comments
Post a Comment