Data structure and algorithms-sorting and finding (Java description)

Source: Internet
Author: User
Tags comparable

In software development, there are two common tasks, one is to find a particular element in a group, and the other is to sort a group of elements in a specific order. We can use a variety of algorithms to accomplish these tasks, and the differences of these algorithms are worthy of careful study, and then we explore these algorithms.

First, find

1.1. Linear Search Method
The linear lookup is to iterate through each element of the array data by index, and if we find the target element to be found and an element in the data, we can find it, and of course, we could improve it by simply returning the found element.

 Public static <t extends comparable<? super t>> boolean  linearsearch (T[] data, int min , it max, t target) {     int index = min;    boolean found = false;     while (!found && index <= max) {//judgment bounds          if (Data[index].compareto (target)  == 0) {             found = true;        }         index++;    }     Return found;} 

1.2, binary lookup

public static <t extends comparable<? super t>> boolean  BinarySearch (T[] data, int min , it max, t target) {     boolean found = false;    int midpoint =  (Min+max)/2;/ /select midpoint position     if (Data[midpoint].compareto (target)  == 0) {         found = true;    } else if (Data[midpoint]. CompareTo (target)  > 0) {        if (min <=  midpoint - 1) {            found =  binarysearch (Data, min, midpoint - 1, target);         }    } else if (Data[midpoint].compareto (target)  >  0) {        if (max >= midpoint + 1) {             found = binarysearch (data, min, midpoint + 1 ,  target);     }}

Second, sort

Sorted into
Sequential sorting: Select, insert, bubble sort;
Logarithmic sort: fast, merge sort;

2.1. Select Sort
By scanning the entire list to find the minimum value, Exchange this value with the value of the first position in the list. Scan the remainder (except the first value) section list and find the minimum value, and then swap it with the value at the second position of the list. Then go on.

public static <t extends comparable<? super t>> void  Selectionsort (t[] data) {    int min ;//defines the minimum value for the storage scan     t  temp;    for (itn index = 0; index < data.length  - 1; index++) {        min = index;// Initializes the minimum value to the first         for (int scan = index + 1;  scan < data.length - 1; scan++) {             if (Data[scan].compareto (Data[min])  < 0) {//if less than the minimum value, assigns the smallest value found to the current minimum                 min =  scan;            }         }        //will find the minimum value and the current first position Exchange         temp  = data[min];        data[min] = data[index];         data[index] = temp;    }}

The outer loop controls where the next minimum value will be stored in the array, and the inner loop looks for the minimum value of the list of remaining parts by scanning all positions that are greater than or equal to the outer loop to make the index.

Here is an interchange function :

Two element exchange position private static <t extends comparable<t>> void swap (t[] data, int index1, int index2) {T temp = da    Ta[index];    DATA[INDEX1] = Data[index2]; DATA[INDEX2] = temp;}

2.2. Insert Sort
The Insert sort algorithm completes the list by repeatedly inserting a particular value into a sorted subset of the list.
Policy: The first two values in the list are sorted by their relative size, the third value of the list is inserted in the appropriate position in the two sorted values of the head, and the fourth value is inserted in the first three sorted positions.

public static <t extends comparable<? super t>> void  Selectionsort (t[] data) {    for (int index = 1; index <  data.length; index++) {        t key = data[ index];//Save this element for the time being         int position = index;// Outer Loop Save Index         //find a larger element to the right position          while (Position > 0 && data[position - 1].compareto (key)  > 0) {            data[position]  = data[position - 1];             position --;        }         data[position] = key;    }} 

2.3, bubble sort
Repeating the comparison list of adjacent elements, If the position of an adjacent element is found to be incorrect, the position of the two elements is exchanged.

 public static <t extends comparable<? super t>> void  Selectionsort (t[] data) {    int position ,scan;    t  temp;    for (position = data.length - 1; position > =0; position --) {        for (Scan = 0; scan  <= position - 1; scan++) {             if (Data[scan].compareto (data[scan+1])  > 0) {                 swap (data,scan, scan + 1);             }         }    }} 

2.4, quick sort

Public static <t extends comparable<t>> void quicksort (T[] data ) {    quicksort (data, 0, data.length-1);} Public static <t extends comparable<t>> void quicksort (T[] data ,  min , max) {    if (Min < max) {         //Creating a partitioned index         int indexofpartition =  partition (Data, min, max);         //recursively sort the left partition          quicksort (data, min, indexofpartition -1);         //recursive sorting of right partitions          QuickSort (Data, indexofpartition + 1, max);     }}public static  <t extends comparable<t>> void parTition (T[] data, int min , int max) {    t  Partitionelement;    int left, right;    int middle  =  (Min+max)/2;    //use intermediate data values as partition elements     partitionelement  = data[middle];    //the first element and the partition element Exchange position     swap (data,middle,min);     left = min;    right = max;     while (left < right) {        // If the element on the left side of the score area element is small, the index right shifts to find the next         while (left< right & & data[left].compareto (partitionelement)  <= 0) {             left ++;        }         //if the element on the right side of the score area is large, move the index left to find the nextElement         while (Data[right].compareto (partitionelement)  >  0) {            right ++;         }        if (left <  right) {            swap (data,left,right);         }    }    //the partition element back to its original location     swap (data, min, right);     return right;}

2.5. Merge sort

Divide the list into approximately equal two parts, and then recursively invoke itself on each part of the list, continuing the recursive decomposition of the list until the basic situation of the recursion is reached, which is the list is split into a 1-length list, by definition, which is now sorted.

Private static <t extends comparable<t>> void mergesort (T[]  Data, int min , int max) {    if (Min < max) {         int mid =  (Min+max)/2;         mergesort (Data,min,mid);         mergesort (data,mid+1 , max);         merge (Data,min,mid,max);     }} Private static <t extends comparable<t>> void merge (T[] data,  int first , int mid, int  last) {    t[] temp  =  (t[]) (New comparable[data.length]);     int first1 = first ,  last1 = mid;    int first2 = mid+1, last2 =  last;    int index = first1;    //copy smaller elements from each subsequence into the temp array until sorted      while (FIRST1&NBSP;&LT;=&NBSP;LAST1&NBSP;&AMP;&AMP;&NBSP;FIRST2&NBSP;&LT;=&NBSP;LAST2) {         if (Data[first1].compareto (Data[first2])  < 0) {             temp[index] = data[first1];             first1++;         } else {            temp[ Index] = data[first2];            first2 ++;        }        index++;     }    //copies the remaining elements from the first subsequence into the temp array     while (first1  <= last1) {        temp[index] = data[first1];         first1++;        index++;     }    //copies the remaining elements from the second subsequence into the temp array     while (first2 <=  LAST2) {        temp[index] = data[first2];         first2++;        index++;     }    //Copy Merge data temp into the original sequence     for (index = first;  index <= last; index++) {        data[index]  = temp[index];    }}


This article is from the "Life Is Beautiful" blog, so be sure to keep this source http://sihai.blog.51cto.com/11115680/1910676

Data structure and algorithms-sorting and finding (Java description)

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.