Several common operation methods of Java arrays (sorting algorithm and lookup) __java Foundation

Source: Internet
Author: User
Tags benchmark stub
Searching for arrays

A lookup is the process of looking for a specific element in an array. Linear Lookup Method

Linear lookup The keyword key to be looked up is compared to the elements in the array. If the match succeeds, the linear lookup law returns the subscript of the element that matches the keyword in the array, or 1 if no match succeeds. The following is a procedure for the linear lookup method:

private static int Linearsearch (int[] list,int key) {
        //TODO auto-generated method stub for
        (int i = 0;i < list . length;i++) {
            if (key = = List[i]) {return
                i
            }
        } return-1;
    }
Int[] list = {1,3,5,7,-3};

        int number1 = Linearsearch (list,1);
        int number2 = Linearsearch (list,7);
        int number3 = Linearsearch (list,-5);

        System.out.println (number1);
        System.out.println (number2);
        System.out.println (NUMBER3);
Output results:
0
3
-1

The linear lookup method compares each element of a keyword array with an average of half of the elements in the array, which is less efficient. Two-point search method

The binary method is another common method of finding array lists. The prerequisite for using the binary lookup method is that the elements in the array must be sorted first.
The binary search method first compares the keywords to the intermediate elements of the array, excluding half of the array elements after each comparison. For an array of 1024 elements, in the worst case, the binary lookup method only needs to compare log2n + 1 = 11 times, while in the worst case the linear lookup is compared 1023 times.
Here is a two-point search procedure:

private static int BinarySearch (int[] list,int key) {
        //TODO auto-generated method stub
        int-low = 0;
        int high = list.length-1;
        Ends the lookup until Low>high has found the keyword, returning-1 while
        (low<=high) {
        int mid = (Low+high)/2;
        if (Key < List[mid]) {High
            = mid-1;
        }
        else if (key > List[mid]) {Low
            = mid + 1;
        }
        else if (key = = List[mid]) {return
            mid;
            }
        }
        return-1;
    }

Follow this method with the following statement

Int[] list = {1,3,5,7,9,10,34,56,78,99};

        int number1 = BinarySearch (list,7);
        int number2 = BinarySearch (list,34);
        int number3 = BinarySearch (list,100);

        System.out.println (number1);
        System.out.println (number2);
        System.out.println (NUMBER3);
Output results:
3
6
-1

The output is just the subscript of the keyword.
The efficiency of the binary method is higher than that of linear lookup, but the array is required to be sorted first. Here we look at the sort of array. Sorting of Arrays

Like lookups, sorting is also a common operation in a computer. Here are two ways of doing this. Select Sort

Suppose you want to sort an array in ascending order. Select the Sort method to find the smallest number in the sequence and then place it at the top of the series. Then select the minimum number in the remaining number, put it behind the first, and so on, until only one number remains in the series.

Look at a sample diagram that will explain more clearly:

The following shows the program for selecting a sort:

public static int[] Selectionsort (int[] arrays) {
        //i represents the number of exchanges, from the above figure can be found in exchange for 9 times for
        (int i = 0; i < arrays.length- 1; i++) {
            int temp = 0;//is used to save the smallest number
            int index = i;///To save the lowest index//find the first

            small value
            ///This cycle, index
            will get the minimum value for (int j = i + 1; j < Arrays.length; J + +) {
                if (Arrays[index] > Arrays[j]) {
                    index = j;
                }
            } //

            swap position, place the first small value found in position I

        ///Assign the minimum value to temp
            temp = Arrays[index];
            arrays[index] = arrays[i];
            Arrays[i] = temp;


    }
        return arrays;  
        }

Follow this method with the following statement

Int[] list = {3,5,23,45,1,66};

        int[] List2 = Selectionsort (list);

        System.out.println (arrays.tostring (List2));
Output results:
[1, 3, 5, 23, 45, 66]

Eg: we can also use Python to write a program to get the same result: Write a function to find the smallest element in the array findsmallest

def findsmallest (arr):
    smallest = arr[0]                <--------store the smallest value
    smallest_index = 0               <--------index to store the minimum value
for I in range (1, len (arr)):
    if arr[i] < smallest:
        smallest = arr[i]
        smallest_index = i return
    SMA Llest_index
def selectionsort (arr):             < sorting pairs of arrays 
NEWARR = [] for
I in range (len (arr)):
smallest = Findsmallest (arr)        <---------Find the smallest element in the array, pop the smallest element of the array,
                                               and add it to the new array
newarr.append Arr.pop ( Smallest)) return
newArr
print Selectionsort ([5, 3, 6, 2, 10])
Insert Sort

Suppose you want to sort a sequence incrementally. The algorithm for inserting a sort method is to sort the values of a sequence by repeatedly inserting a new element in the sorted subsequence.

The following shows the use of the Insert sort algorithm to sort the sequence {2,9,5,4,8,1,6}:

private static int[] Insertionsort (int[] list) {/
        /TODO auto-generated Method Stub

        //1th number is definitely ordered, starting from the 2nd number, Insert the ordered sequence
        for (int i = 1;i < list.length;i++) {

            //Remove number I, and before the number of i-1, insert the appropriate position
            int currentelement = list[i];< C5/>int J;

            Since the number of i-1 is an ordered sequence from small to large, so long as the current comparison (List[j]) is larger than currentelement, the number is moved back to a for

            (j = i-1;j >= 0&&) > currentelement;j--) {
                list[j+1] = list[j];
                }

            List[j + 1] = currentelement;
            }

        return list;

    }

Follow this method with the following statement:

        Int[] list = {2,9,5,4,8,1,6,-5};

        int[] List2 = Insertionsort (list);

        System.out.println (arrays.tostring (List2));
Output results:
[ -5,1, 2, 4, 5, 6, 8, 9]
Note:


The direct insertion sort method is best when the data to be sorted is basically orderly.

The time complexity of selecting sorting, stacking, merging and Radix algorithms is independent of the initial order

N-Characters in the worst case requires at least n-1 22 Exchange to arrange the sequence bubbling sort

In each traversal of the array, compare the two elements that are adjacent to each other. If this pair of elements is in descending order, the values are exchanged, otherwise the values remain unchanged.

Looking at an example diagram, sometimes the diagram is clearer than the text:

The following shows the use of the bubble sort algorithm to sort the sequence {2,9,5,4,8,1,6}:

public static double[] Bubblesort (double[] arrays) {
        int temp;
        Here I represents the exchange of several times, such as the above figure 52 in exchange for the first in a total of three exchanges for
        (int i = 0;i<arrays.length-1;i++) {
        //from the backward in order to compare the number of adjacent two, after traversing once, Place the number I in the array in the J position
        , where J indicates where it is located after the exchange, for example, for the first time, it's because 52 and 59 are switched to the 3 position
        ///The last number is compared to the previous number, until I's position is stopped for

            (j=3). int  j = arrays.length-1;j>i;j--) {
            //Compare the adjacent two numbers and swap positions
                if (arrays[j-1] > Arrays[j]) {
                    temp = ARRAYS[J-1];
                    ARRAYS[J-1] = arrays[j];
                    ARRAYS[J] = temp;
                }

        }} return arrays;

    }

Follow the above algorithm with the following statement:

Double[] MyList = {5.0, 4.4, 1.9, 2.9, 3.4, 2.9, 3.5};
Double []list = Bubblesort (myList);
System.out.println ("My list after sort is:" + arrays.tostring (list));
Output results: My
list after sort is: [1.9, 2.9, 2.9, 3.4, 3.5, 4.4, 5.0]
Quick Sort

Quick Sort is the sort of exchange class, such as in the line, the teacher said: "The first classmate out, the other students to the first classmate as the center, than his short all ranked on the left, higher than his full row on the right." "That's a quick sort of a trip. As you can see, a quick sort is centered on a "pivot", dividing the sequence into two parts, one side of the pivot is all smaller (or less than equal), and the other side is all larger (or greater than equal).

The fast sorting algorithm uses a kind of divide-and-conquer strategy, which is usually referred to as the partition method, the basic idea is: 1, first take out a number of numbers as the base number, 2, the partition process, will be more than the number of large numbers to its right, less than or equal to its number all put on its left; 3, Repeat the second step to the left and right intervals until the interval is only one number.

As an example of a simple array, let's take a look at the sorting process for the fast sort algorithm:

again to array[0 ... 1] and array[3..4] Repeat the above steps on the line.

Note: Only the values of I and J are changed in a single lookup, and thevalue of x remains unchanged.

The above steps are summarized as follows:

1, i=l,j=r,x=array[i];
2, j--from the rear to find less than equals x number, found after using array[j] instead of array[i];
3, i++ from the front to find greater than the number of X, found after the use of array[i] instead of array[j];
4, the repeated execution of 2, 3 steps until i=j, and finally write the benchmark number Array[i].

The following shows how to use the quick Sort algorithm to sort the array [2,7,9,3,5,6,1,8]:

private static int[] Quicksortmethod (int[] array, int left, int right) {//TODO auto-generated stub if (left<right) {int i = left;//left node, array first number of index int j = right;//Right node, array last number of index int x = Array[i]; X is the base number/pivot, all with the benchmark number to do comparison standard//do a loop, when I=j, write the datum number to Array[i] while (I&LT;J) {//loop from right to left to find less than or equal
                Number of x, find the right node to move forward one while (i<j&&array[j]>=x) {j--; ///Assign the number of the corresponding index to the number of the left node, note that the assignment to the x,x is invariant, and the left node moves forward an if (i<j) {array[i] = AR
                    RAY[J];
                i++;
                    //loop from left to right to find the number greater than or equal to X, find the left node move forward one while (i<j&&array[i]<x) {
                i++; ///The number assigned to the right node of the corresponding index, note that the assignment to the x,x is invariant, and the right node moves forward an if (i<j) {array[j] = AR
                    Ray[i];
                j--;
  }   
            }          The datum number is filled to I array[i] = x;
            Recursively sort Quicksortmethod (array, left, i-1) on both sides of the datum number;
        Quicksortmethod (array, i+1, right);
    } return array; }

Follow the above algorithm with the following statement:

Int[] array = {2,7,9,3,5,6,1,8};
        int left = 0;
        int right = Array.length-1;
        int[] List = Quicksortmethod (array,left,right);
        System.out.println (arrays.tostring (list));
Output results:
[1, 2, 3, 5, 6, 7, 8, 9]
Hill Sort

Hill (Shell) sort is also known as narrowing the incremental sort , which is an insert sort . It is a power-enhanced version of the direct insertion sort algorithm .

The method is due to a DL. The shell was named after it was introduced in 1959.

The basic idea of Hill sort is:

The records are grouped by step Gap , which is sorted by a direct insertion sort method for each group of records.
As the step gradually decreases, the grouped groups contain more and more records, and when the value of the step is reduced to 1 o'clock, the whole data is grouped together into a set of ordered records, then the sorting is completed.

taking a simple array for example, let's take a look at the sorting process of the Hill sort algorithm:

Take the array {26, 53, 67, 48, 57, 13, 48, 32, 60, 50} as an example, the step sequence is {5,2,1}
Initialization keywords: [26, 53, 67, 48, 57, 13, 48, 32, 60, 50]

Gap length is generally one-second of the array lengths ;

The final sort result:
13 26 32 48 48 50 53 57 60 67

The basic algorithm of hill sorting is implemented as follows:

private static int[] Shellsort (int[] array) {//TODO auto-generated method stub
        int temp = 0;
        Int J; Step gap, the step will undergo three changes, the 10/2=5, 5/2=2, 2/2=1//increment sequence of the last increment value must be equal to 1 to the line,//In this example, the array will go through the three sort process, which is the function of the first loop//Will
        A group of elements that are 5 apart from Gap, can be divided into 5 groups for (int gap = array.length/2;gap>0;gap/=2) {//To sort each group by the method of direct insertion sort. 
                Traverse the value from subscript to gap to the last value for (int i = gap;i<array.length;i++) {//record every time the value of Mark as Gap
                temp = Array[i]; Traverse the value from subscript 0 to the value for gap (j = i-gap;j>=0;j-=gap) {//Direct insert sort.
                    Compare the values of both, then the smaller and larger exchange positions if (Temp<array[j]) {Array[j+gap] = array[j];
                    } else {break;
            } Array[j+gap] = temp;
    } return array; }

Follow the above algorithm with the following statement:

Int[] Array = {9, 1, 2, 5, 7, 4, 8, 6, 3, 5};
int[] List = Shellsort (array);
System.out.println (arrays.tostring (list));

Output results:

[1, 2, 3, 4, 5, 5, 6, 7, 8, 9]
order of two-dimensional arrays

The two-dimensional array is sorted first by row, and then by column. such as arrays:
{{4, 2}, {1, 7}, {4, 5}, {1, 2}, {1, 1}, {4, 1}}

Package com.example.exercise7_4;
Import Java.util.Arrays;

Import Java.util.Scanner; public class Exercise2 {public static void main (string[] args) {int[][] array = {4, 2}, {1, 7}, {4,
        5}, {1, 2}, {1, 1}, {4, 1}};
        Sort (array);
    PrintArray (array); } private static void sort (int[][] array) {//TODO auto-generated method stub for (int i = 0;i <
            array.length;i++) {Double currentmix = array[i][0];

            Declare a variable record of which line int currentmixindex = i;
                        for (int j = I;j < array.length;j++) {if (Currentmix > array[j][0] | | currentmix = = Array[j][0]
                      && array[currentmixindex][1] > array[j][1]) {currentmix = array[j][0];
                Currentmixindex = j;
              }///Swap List[i] with List[currentminindex] if necessary;
           if (Currentmixindex!= i) {     int temp0 = array[currentmixindex][0];
                int temp1 = array[currentmixindex][1];
                Array[currentmixindex][0] = array[i][0];
                ARRAY[CURRENTMIXINDEX][1] = array[i][1];
                Array[i][0] = temp0;
             ARRAY[I][1] = Temp1;
         }} private static void PrintArray (int[][] array) {//TODO auto-generated method stub
        for (int i = 0; i < Array.Length i++) {System.out.println (array[i][0] + "," + array[i][1]);

 }
    }

}
Related Article

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.