Sorting algorithm _ Sorting algorithm

Source: Internet
Author: User
Tags array length

First, insert sort

Each step inserts a record to be sorted, in its order code size, into the appropriate position in the previously sorted sequence of words (after finding the appropriate position from the rear) until all the inserts are sorted out.

     * Insert Sort
     * Starting with the first element, the element can be thought to have been sorted out of the next element, scanned from the back in the sorted element    
 * Sequence
     * If the element (sorted) is greater than the new element, move the element to the next position repeat step 3. Until you find the    
 element that has been sorted less than or equal to the new element, insert the new element into the location repeat step 2 * To be
     sorted array
    static void Insertsort (int[] numbers) 
        int size = numbers.length;
        int temp = 0;
        int j = 0;
        for (int i = 0; i < size; i++)
            temp = numbers[i];
            If temp is smaller than the previous value, move the previous value back for
            (j = i; j > 0 && Temp < numbers[j-1]; j--)
                Numbers[j] = Nu MBERS[J-1];
            NUMBERS[J] = temp;

Two, Hill algorithm

First, the whole sorted record sequence is divided into several sub sequences for direct insertion sort, and then the whole records are inserted into order directly after the records are "basically ordered" in the entire sequence.

    /** * Hill Sort principle: According to the demand, if you want the results to range from large to small, it will first group the array, then move the larger value to the front, the smaller value to the back, and finally the entire array to be inserted, so that you can reduce the data exchange and shift with the insertion sort from the start The number of moves * can be said Hill sort is the enhanced version of the insert sort take the array 5, 2, * 8, 9, 1, 3,4, the array length is 7, when increment is 3 o'clock, the array is divided into two sequences * 5,2,8 and 9,1,3,4, the first order, 9 and 5 comparisons, Comparison between 1 and 2, 3 and 8, 4 and a comparison of the array values of the smaller * increment of the subscript value * This example is arranged from large to small, so the large will be in front, the first order after the array is 9, 2, 8, 5, 1, 3,4 * The first time after the increment value changes
        For 3/2=1, the array is then inserted to sort, implementing the arrays from large to small/public static void Shellsort (int[] data) {int j = 0;
        int temp = 0; Shorten the step length to the original half for (int increment = DATA.LENGTH/2; increment > 0; increment/= 2) {f
                or (int i = increment i < data.length; i++) {temp = Data[i]; for (j = i; J >= increment; J-= increment) {if (Temp > Data[j-increment)
                    )//If you want to change from small to large platoon just modify here {data[j] = data[j-increment];
                } else    {break;
            } Data[j] = temp; }

Third, bubble sort

Bubble sort is a simple sort algorithm. It repeatedly visits the sequence to be sorted, compares two elements at a time, and swaps them if their order is wrong. The task of visiting the series is repeated until no further exchange is needed, which means that the sequence has been sorted. The algorithm is named because the smaller elements float slowly through the exchange to the top of the sequence.

     * * Bubble sort compares adjacent elements. If the first one is bigger than the second one, swap them both.
     * Do the same work for each pair of adjacent elements, from the first pair to the end of the last pair. At this point, the last     
 * element should be the largest number. Repeat the above steps for all elements except the last one.
     * Continue to repeat the previous steps for less and fewer elements until no pair of digits need to be compared.
     * @param numbers integer array that needs to be sorted *
    /public static void Bubblesort (int[] numbers)
        int temp = 0;
        int size = Numbers.length;
        for (int i = 0; i < size-1. i++)
            (int j = 0; J < size-1-I. j)
                if (numbers[j > numbers[j + 1])//Exchange two number position
                    temp = numbers[j];
                    NUMBERS[J] = numbers[j + 1];
                    Numbers[j + 1] = temp;

Four, quick sort

By sorting the records to be sorted into two separate parts, where some of the records have less keywords than the other, the two sections are sorted until the entire sequence is ordered.
A quick sort is generally considered to be the best in the ranking method of the same order of magnitude (O (nlog2n)). But if the initial sequence is ordered or basically ordered by the key code, the fast sort is reduced to bubble sort. In order to improve it, the benchmark record is usually selected by the "three-way Method", which adjusts the center of the two endpoints of the sorted interval and the midpoint of three key codes to the Fulcrum record. A quick sort is an unstable sort of method.

     /** * Find out the central axis (the default is the lowest bit low) in the numbers array after the sort of location * * @param numbers with find array * @param low start position * @pa
        Ram high end position * @return Axis position * * public static int getmiddle (int[] numbers, int low,int high) { int temp = Numbers[low];
        The first of the array is in the axis while (low < high) {while (Low < high && Numbers[high] > Temp)
        } Numbers[low] = numbers[high];//is moved to the low-end while (Low < high && Numbers[low] < temp) smaller than the middle axis
        {low++; } Numbers[high] = Numbers[low]; Higher than the central axis of the record moved to the high-end} Numbers[low] = temp; Middle axis record to tail return low;
        Returns the position of the middle axis} public static void QuickSort (int[] numbers, int low, int high) {if (Low < high) {int middle = getmiddle (numbers, low, high)///numbers array for one point two quickSort (numbers, lo W, middle-1); Recursive ordering of low field tables QuicksoRT (Numbers, middle + 1, high);
 Recursively Sort high field tables}

V. Choice of sorting

In the set of numbers to be sorted, select the smallest number to be exchanged with the number of the first position, and then find the smallest interchange with the second position in the remaining number, so that it loops to the penultimate number and the last number comparison.

     * Select sorting algorithm
     * Find the smallest element in the unordered sequence, hold it to the start of the sort sequence  
     * and then continue to look for the smallest element from the remaining unordered elements, and then place it at the end of the sort sequence. 
     * And so on until all the elements are sorted. 
     * @param numbers */public
    static void Selectsort (int[] numbers)
    int size = numbers.length;// Array length
    int temp = 0;//intermediate variable for

    (int i = 0; i < size; i++)
        int k = i;   Position to be determined
        //select number for
        (int j = size-1; j > i; j--)
        if (NUMBERS[J) < Numbers[k])
            k = j;
        Exchange two numbers
        temp = numbers[i];
        Numbers[i] = numbers[k];
        NUMBERS[K] = temp;

Six, heap sorting algorithm

Heap ordering is a sort of tree selection, which is an effective improvement of direct selection sort.
The definition of a heap: a sequence with n elements (h1,h2,..., HN) that is called a heap if and only if it satisfies (hi>=h2i,hi>=2i+1) or (hi<=h2i,hi<=2i+1) (i=1,2,..., N/2). Only the heap that satisfies the former condition is discussed here. As you can see from the definition of the heap, the top element of the heap (that is, the first element) must be the maximum item (the large top heap). A complete binary tree can visually represent the structure of a heap. The top of the heap is the root and the other is Zuozi and right subtree.
Thought: Initially the sequence of numbers to be sorted is considered to be a sequential two-tree, which adjusts their storage order to make it a heap, at which point the number of root nodes of the heap is the largest. The root node is then exchanged with the last node of the heap. Then readjust the number of front (n-1) to make it a heap. And so on, until there are only two nodes in the heap, and exchange them, and finally get an ordered sequence of n nodes. From the description of the algorithm, heap sequencing requires two processes, one is to build a heap, and the other is to exchange positions between the top of the heap and the last element of the heap. So the heap sort has two function components. The first is to build the seepage function of the heap, and the second is to call the function of the infiltration function to realize the sort.

Merging sorting algorithm

The merge Sort method combines two (or more) ordered tables into a new ordered table, which divides the sequence into several subgroups, and each subsequence is ordered. Then the ordered Subsequence is merged into the whole ordered sequence.

     /** * Merge Sort * Introduction: Merging two (or more) ordered tables into a new ordered table divides the sequence to be sorted into several subcategories, each of which is ordered. Then the ordered Subsequence is merged into the whole ordered sequence * time complexity is O (nlogn) * Stable sort mode * @param nums array * @return output ordered array/public s
        Tatic int[] Sort (int[] nums, int low, int high) {int mid = (low + high)/2;
            if (Low < high) {//left sort (nums, low, mid);
            Right sort (nums, mid + 1, high);
        Merge merges Around (Nums, low, Mid, high);
    return nums; /** * Sort the number of low to high positions in the array * @param nums array * @param low the start position to row * @param mid to row intermediate position *  @param high ready to row end position/public static void merge (int[] nums, int low, int mid, int high) {int[] temp = new
        Int[high-low + 1];

        int i = low;//left pointer int j = mid + 1;//right pointer int k = 0;
               Move the smaller number first to the new array while (I <= mid && J <= High) {if (Nums[i] < nums[j]) { temp[k++] = nums[i++];
            else {temp[k++] = nums[j++];
        ()///Move the remaining left number into the array while (I <= mid) {temp[k++] = nums[i++];
        ///Move the remaining number on the right side into the array while (J <= High) {temp[k++] = nums[j++];
        ///Overwrite the new array with the Nums array for (int k2 = 0; K2 < temp.length; k2++) {nums[k2 + low] = Temp[k2];

Viii. Summary

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: 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.