The function of the array in the data structure is very important, so to learn the data structure and algorithm, first of all, we need to understand and familiar with the logarithm group. The example uses object-oriented thinking and operates on an array.
Declares an array of type long, in which the element is within length.
Private long[] arr;
private int element;
1 //no parameter constructor2 PublicMyArray () {3arr =New Long[50];4 }5 6 //Parametric Constructors7 PublicMyArray (intmaxSize) {8arr =New Long[maxSize];9}
constructor Function
1 Public void Insert (long value) {2 arr[element] = value; 3 element++; 4 }
Basic Insert Operation
1 Public voidInsertOrder (Longvalue) {2 inti;3 for(i=0;i<element;i++){4 if(arr[i]>value) {5 Break;6 }7 }8 for(intj=element;j>i;j--){9ARR[J] = arr[j-1];Ten } OneArr[i] =value; Aelement++; -}
Sequential Insertion
1 Public void display () {2 System.out.println ("["); 3 for (int i=0; i<element;i++) 4 {5 System.out.println (arr[i]+ ""); 6 }7 System.out.println ("]"); 8 9 }
Print Array
1 Public intSearchLongvalue) {2 inti;3 for(i=0; i<element; i++){4 if(Value = =Arr[i]) {5 Break;6 }7 }8 if(i = =Element) {9 return-1;Ten}Else One returni; A}
Find by Value
1 Public LongGetValue (intindex) {2 if(Index >= Element | | Index < 0){3 throws Newarrayindexoutofboundsexception ();4 }5 Else{6 returnArr[index];7 }8}
Find by index
1 Public intBinarySearch (Longvalue) {2 intMiddle = 0;3 intLow=0;4 intpow=element;5 while(true){6Middle= (Pow+low)/2;7 if(Arr[middle] = =value) {8 returnMiddle;9}Else if(low>POW) {Ten return-1; One}Else{ A if(arr[middle]>value) { -POW = middle-1; -}Else{ theLow = Middle+1; - } - } - } +}
Binary Method Search
1 Public voidDeleteintindex) {2 if(Index >= Element | | Index < 0){3 throws Newarrayindexoutofboundsexception ();4}Else{5 for(inti = index; i<element; i++){6Arr[index] = arr[index+1]7 }8element--;9 }Ten}
Delete based on index
1 Public voidUpdateintIndexintNewData) {2 if(Index >= Element | | Index < 0){3 throws Newarrayindexoutofboundsexception ();4}Else{5Arr[index] =NewData;6 }7 }8}
Modifying array values
Simple operation of arrays