Java-based array common operations, java-based array

Source: Internet
Author: User

Java-based array common operations, java-based array

Common Operations on Arrays

1. Calculate the maximum and minimum values in the array.

Idea: assume that the element whose subscript is 0 is the maximum value, traverse the array, and compare it with max in sequence. If an element is bigger than this max, assign this value to max. The minimum value is the same.

1 public class TestArray {2 public static void main (String [] args) {3 int [] arr = {234,576, 67 }; 4 int max = arr [0]; 5 int min = arr [0]; 6 for (int I = 0; I <arr. length; I ++) {7 if (arr [I]> max) {8 max = arr [I]; 9} 10 if (arr [I] <min) {11 min = arr [I]; 12} 13} 14 System. out. println ("the maximum value in the array is:" + max); 15 System. out. println ("the minimum value in the array is:" + min); 16} 17}

 

2. Check whether an element exists in the array.

1 import java. util. extends; 2 public class TestArray {3 public static void main (String [] args) {4 blocks in = new loads (System. in); 5 int [] arr = {234,576, 67}; 6 System. out. println ("Enter the element you want to search for"); 7 int element = in. nextInt (); 8 int I, flag = 0; 9 for (I = 0; I <arr. length; I ++) {10 if (arr [I] = element) {11 flag = 1; 12 break; 13} 14} 15 if (flag = 1) {16 System. out. println ("the subscript of the element to be searched is:" + I); 17} else {18 System. out. println ("the element you are looking for does not exist"); 19} 20} 21}

(2) Use the binary search method to find whether an element exists in the array.

Premise: the array to be searched must be ordered (size ordered)

Principle: Compare the element to be searched with the element in the middle of the array. If the value is greater than the middle element, search on the right. If the value is smaller than the middle element, search on the left.

 1 public static int binarySearch(int[] arr,int ele){ 2         int left=0; 3         int right=arr.length-1; 4         int mid; 5         int index=-1; 6         while(left<=right){ 7             mid=(left+right)/2; 8             if(arr[mid]==ele){ 9                 index=mid;10                 break;11             }else if(arr[mid]<ele){12                 left=mid+1;13             }else if(arr[mid]>ele){14                 right=mid-1;15             }16         }17         return index;18     }

 

3. Sort Arrays

(1) Bubble Sorting

Principle: Compare adjacent elements, small forward, large backward, maximum index of the maximum value

Analysis: For the first comparison, the maximum value will be placed at the largest index in the future.

For the second comparison, because the maximum value has been determined, you only need to compare the first n-1 elements to determine that the second largest value is at the second index.

Determine the third percentile, the fourth largest value .............

Conclusion: N numbers come to the queue, the two are relatively small front, the outer loop n-1, the inner loop n-1-i

 

1 public class TestArray {2 public static void main (String [] args) {3 int [] arr = {10, 3, 8, 1, 6 }; 4 // compare round number of outer loop control 5 for (int I = 0; I <arr. length-1; I ++) {6 // The inner loop controls the number of comparisons per round 7 for (int j = 0; j <arr. length-1-i; j ++) {8 if (arr [j]> arr [j + 1]) {9 int temp = arr [j]; 10 arr [j] = arr [j + 1]; 11 arr [j + 1] = temp; 12} 13} 14} 15 // traverse the array 16 for (int I = 0; I <arr. length; I ++) {17 System. out. println (arr [I]); 18} 19} 20}

 

 

(2) Select sorting

Principle: Start from the subscript 0 and compare it with the following elements in sequence. If the following element is smaller than the subscript 0, the position is changed. Compare the element with the element whose subscript is 0 with the following one. After the first completion, the minimum value appears at index 0.

Example: {10, 3, 8, 1, 6}

The first round of comparison starts from 0 subscript elements and compares them with the following elements in sequence. First, 10 and 3 are compared. 10 <3, the position of the switch, and the element of subscript 0 is changed to 3, {3, 10, 8, 1, 6}; compare 3 and 8, 3 <8, without transposition; 3 and 1 for comparison, 3> 1, transposition

{, 6}, then compare 1 with 6, 1 <6, without changing the position. End of the first round, {, 3, 6}

In the second round of comparison, the element of subscript 0 has been determined to be the minimum value in the previous round. This round of comparison starts from subscript 1. First, 10 and 8 are compared, and the positions are {, 10, 3, 6 }; comparison between 8 and 3: {1, 3, 10, 8, 6}, 3, and 6. At the end of the second round, determine that the second-to-last element is at the position of subscript 1.

........

Compare the length-1 round.

1 public class TestArray {2 public static void main (String [] args) {3 int [] arr = {10, 3, 8, 1, 6}; 4 for (int I = 0; I <arr. length-1; I ++) {5 for (int j = I + 1; j <arr. length; j ++) {6 if (arr [I]> arr [j]) {7 int temp = arr [I]; 8 arr [I] = arr [j]; 9 arr [j] = temp; 10} 11} 12} 13 // traverse array 14 for (int I = 0; I <arr. length; I ++) {15 System. out. println (arr [I]); 16} 17} 18}

 

4. Delete elements from the array

(1) Delete an element based on the subscript (fill 0 in the blank space)

1 public static void delete(int[] arr,int index){2         for(int i=index;i<arr.length-1;i++){3             arr[i]=arr[i+1];4         }5         arr[arr.length-1]=0;6         System.out.println(Arrays.toString(arr));7     }

 

(2) Delete the elements in the array based on the input elements.

 1 public static void delete(int[] arr,int ele){ 2         int index=-1; 3         for(int i=0;i<arr.length;i++){ 4             if(arr[i]==ele){ 5                 index=i; 6             } 7         } 8         for(int i=index;i<arr.length-1;i++){ 9             arr[i]=arr[i+1];10         }11         arr[arr.length-1]=0;12         System.out.println(Arrays.toString(arr));13     }

 

 

The following describes some common operations on arrays in APIs.

In java, except classes and interfaces under the java. lang package can be directly used, classes or interfaces under other packages must be previewed.
Java. util. Arrays class: This class contains various methods used to operate Arrays (such as sorting and searching.

These are static methods, which can be used directly by class name and method name. Here we use an array of the int type as an example.

1. Fast sorting of Arrays

Arrays. sort (int [] arr); sort the input array in ascending order by default.

2. returns the string representation of the specified array content.

Arrays. toString (int [] arr );

3. Use the Binary Search Method to Determine the subscript of an element in the array.

Arrays. binarySearch (int [] arr );

4. Assign the specified int value to each element of the specified int array.

Arrays. fill (int [] arr, int val );

5. Copy the specified array, intercept or fill it with 0 (if necessary), so that the copy has the specified length.

Arrays. copyOf (int [] arr, int newLength); its return value is an array

6. Copy the specified range of the specified array to a new array. It contains the starting position but not the ending position.

Arrays. copyOfRange (int [] arr, int from, int to); its return value is an array

 

Other array knowledge:

1. command line parameters: You can pass in the parameter value for the main method when executing the java command.

Usage: when running a java command, input the command line parameter: java class name "value 1" value 2 "...

Public static void main (String [] args) {}, we can see that the main method is a method with parameters, and the parameter is a String array. When the main method is used to pass values, all input values are saved in the args character array.
Note: multiple parameter values are separated by spaces. The parameter value is saved to the string array and passed into the main method. The subscript starts from scratch.
When obtaining command line parameters, you must note that the subscript cannot be out of bounds. The maximum subscript should be the number of parameters-1

public static void main(String[] args){2         for(int i=0;i<args.length;i++){3                 System.out.println(args[i]);4         }5 }

 

 

2. variable parameters

Variable parameters are a new feature after java. They can represent zero to multiple variables of the same data type. They are used to solve the problem of excessive method overloading caused by changes in the number of parameters.

Note: 1. variable parameters can only be used for formal parameters (when a method is defined). variable parameters can be processed as arrays.

2. A method can have only one variable parameter at most. A variable parameter must be the last parameter.

3. When calling a method with a variable parameter, the data type must correspond to the variable parameter type.

 1 public class Test1 { 2     public static void main(String[] args){ 3         double sum=add(4,2.1,3.4,1.2); 4         System.out.println(sum); 5     } 6     public static double add(int a,double...b){ 7         double sum=a; 8         for(int i=0;i<b.length;i++){ 9             sum+=b[i];10         }11         return sum;12     }13 }

 

 

Example:

Idea: determine the number not 0, which can open up a new array; extract the content from the old array and assign it to the new array.

 

 1 public class Test1 { 2     public static void main(String[] args){ 3         int oldArr[]={1,3,4,5,0,0,6,6,0,5,4,7,6,7,0,5}; 4         int[] arr=mergeArrays(oldArr); 5         System.out.println(Arrays.toString(arr)); 6     } 7     public static int[] mergeArrays(int[] oldArr){ 8         int count=0; 9         for(int i=0;i<oldArr.length;i++){10             if(oldArr[i]!=0){11                 count++;12             }13         }14         int[] newArr=new int[count];15         int index=0;16         for(int i=0;i<oldArr.length;i++){17             if(oldArr[i]!=0){18                 newArr[index]=oldArr[i];19                 index++;20             }21         }22         return newArr;23     }24 }

 

 

 

 

2. Use the binary method to find elements in an ordered array. The returned index is found and no output-1 exists. Implement with recursion

 

 1 public class Test1 { 2     public static void main(String[] args){ 3         int[] arr={1,2,3,4,5,6,7,8}; 4         int index=binarySearch(arr,6,0,arr.length-1); 5         System.out.println(index); 6     } 7     public static int binarySearch(int[] arr,int ele,int left,int right){ 8         int mid=(left+right)/2; 9         if(arr[mid]==ele){10             return mid;11         }else if(arr[mid]<ele){12             return binarySearch(arr,ele,mid+1,right);13         }else if(arr[mid]>ele){14             return binarySearch(arr,ele,left,mid-1);15         }16         return -1;17     }18 }

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.