JAVA array algorithm (copy, search, insert), java Array
I. Copy an array algorithm
// Array replication algorithm public class Test {public static void main (String [] args) {int [] arrA = {100,800,500,600,700}; int [] arrB = new int [arrA. length]; // use the for loop to copy the corresponding value of A to B for (int I = 0; I <arrA. length; I ++) {arrB [I] = arrA [I];} // output arrB for (int I = 0; I <arrB. length; I ++) {System. out. println (arrB [I]) ;}}
Running result:
Ii. Search for Array Algorithms
// Array search algorithm // find whether the student exists import java. util. users; // import the Scanner public class Test {public static void main (String [] args) {users in = new users (System. in); System. out. print ("Enter the student you want to search for:"); String name = in. next (); String [] arr = {"Wang 'er", "Zhang San", "Li Si", "Wang Wu", "Liu Ma Zi "}; // Student name int yes = arr. length; // record an impossible subscript for (int I = 0; I <arr. length; I ++) {if (name. equals (arr [I]) {yes = I; break ;}} if (yes <arr. length) {System. out. println ("Student:" + name + ", the value is" + yes);} else {System. out. println ("Student:" + name + "nonexistent ");}}}
Running result:
3. insert an array algorithm
// Array Insertion Algorithm import java. util. role; public class Test {public static void main (String [] args) {role in = new role (System. in); int [] arr = {199,433,}; System. out. println ("Enter the value you want to insert:"); int num = in. nextInt (); arr [arr. length-1] = num; for (int I = arr. length-1; I> 0; I --) {if (arr [I] <arr [I-1]) {int t = arr [I]; arr [I] = arr [I-1]; arr [I-1] = t;} else {break;} // output for (int I = 0; I <arr. length; I ++) {System. out. println (arr [I]) ;}}
Running result: