Array sorting, element search and element addition
•
Java
import java. util. Arrays;
public class array_sort { public static void main(String args[]) throws Exception{ int array[]={2,5,-2,6,-3,8,-7,-9,4}; System.out.print("初始数组为:"); printArray(array); Arrays.sort(array); System.out.print("数组排序结果为:"); printArray(array); int index=Arrays.binarySearch(array,6); System.out.println("元素2在"+index+"位置"); array=insertElement(array,3,20); System.out.println("插入元素后的数组为:"); printArray(array); } public static void printArray(int array[]){ for(int i=0;i<array.length;i++){ if(i!=0){ System.out.print(","); } System.out.print(array[i]); } System.out.println(); } public static int[] insertElement(int array[],int index,int value){ int length=array.length; int array1[]=new int[length+1]; for(int i=0;i< index;i++){ array1[i]=array[i]; } array1[index]=value; for(int i=index+1;i<array1.length;i++){ array1[i]=array[i-1]; } return array1; } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码