How do I sort an array and search for its elements?
The following example shows how to use sort()
the and binarySearch()
methods to complete a task. The user-defined method is printArray()
used to display the array output:
Package com. Yiibai;Import Java. util. Arrays;PublicClassArraysortandsearch{PublicStaticvoidMain(String args[])Throws Exception{int array[]={2,5,-2,6,-3,8,0,-7,-9,4}; Arrays.Sort(Array);PrintArray("Sorted Array", array);int index= Arrays.BinarySearch(Array,2); System. Out.println("Found 2 @"+ Index);}PrivateStaticvoidPrintArray(String message,int array[]){System. Out.println(Message+": [Length:"+ Array. length+"]");For(int I=0; I< array. length; I++){If(I!=0){System. Outprint () System.out.< Span class= "token function" >print (Array[i]} system.out. Println}}
Java
Execute the above example code to get the following results-
Sorted array: [length: 10]-9, -7, -3, -2, 0, 2, 4, 5, 6, 8Found 2 @ 5
ShellLinear Search
The following example shows a search array element that uses a linear search.
Package com. Yiibai;PublicClassArraySortAndSearch2{PublicStaticvoidMain(String[] Args){Int[] A={2,5,-2,6,-3,8,0,-7,-9,4};int target=0;For(int I=0; I< a. length; I++ { if (a[i] = = Target) {System. Out. println("Element found at index" + i); break; } } }}< /c6>
Java
Execute the above example code to get the following results-
Element found at index 6
ShellBubble Sort
The following example shows using the bubbling sort method to sort the array elements.
Package com. Yiibai;PublicClassArraySortAndSearch3{StaticvoidBubblesort(Int[] Arr){int n= Arr. length;int Temp=0;For(int I=0; I< n; I++){For(Int J=1; J<(n-I); J++){If(arr[j-1]> Arr[j]){Temp= Arr[j-1]; Arr[j-1]= Arr[j]; Arr[j]= Temp;}}}}PublicStaticvoidMain(String[] Args){int arr[]={2,5,-2,6,-3,8,0,-7,-9,4}; System. Out.println("Array before Bubble Sort");For(int I=0; I< arr. length; I++){System. Out.Print(arr[I]+" ");} System. Out.println();Bubblesort(arr); System. Out.println("Array after Bubble Sort");For(int i = 0; I < arr. length; I+ +) {System. Out. Print(arr[i] + ""); } }}< /c6>
Java
Execute the above example code to get the following results-
Array Before Bubble Sort2 5 -2 6 -3 8 0 -7 -9 4 Array After Bubble Sort-9 -7 -3 -2 0 2 4 5 6 8
Java array Sorting and searching