Top ten sorting algorithms (Java implementation) __ algorithm

Source: Internet
Author: User
Tags pow sorts
Ten common sorting algorithms (Java Implementation)"Preface" Recently in the study of algorithms, this blog for their own review and use for the convenience of the vast number of programmers students. This code is to achieve their own, through the comparison of the classical method of verification, if there is a mistake to ask the reader to make timely.

-"Comparative analysis Chart" First, we first compare the characteristics of the top ten sorting algorithms:

(i). Bubble sort (optimization)

"topic" For an int array, write a bubble sort algorithm that sorts the array elements.
Given an int array A and the size n of the array, return the sorted array. Bubble sort, as the name suggests, from the bottom up traversal, each traversal to fixed a minimum value plus a flag bit, when a trip bubble sort without element exchange, the bubble ended, the element is ordered, can effectively reduce the number of bubbles.

Import java.util.*;

public class Bubblesort {public
    int[] Bubblesort (int[] A, int n) {
        //bubble sort: From back forward (from bottom to top) like bubbling
        //with flag as the mark, Whether the tag array has been sorted completes
        Boolean flag = true;
        Fixed the left digit for
        (int i=0; i<n-1&flag; i++) {
            flag = false;
            Traverse for (
            int j=n-2;j>=i;j--) {

                if (a[j]>a[j+1]) {
                    swap (a,j,j+1)
                    from the back (below) forward (up); Flag = true;
                }
            }

        return A;

    }
    Arrays are passed by reference, changing arrays in functions
    private void Swap (int[] A,int i,int j) {
        int temp = a[i];
        A[i] = a[j];
        A[J] = temp;
    }
}

(b). Simple selection Sort

"topic" For an int array, write a select sort algorithm that sorts the array elements.
Given an int array A and the size n of the array, return the sorted array. 1. "Initial ascending order": Exchange 0 times, time complexity of O (n); "Initial descending order": Swap n-1 times with a time complexity of O (n^2). "Characteristics": the exchange of mobile data less times, more times.

Import java.util.*;
/**

**/Public
class Selectionsort {public
    int[] Selectionsort (int[] A, int n) {
       //Simple Select sort algorithm, sorted result is an ascending array c5/>//record minimum subscript value
        int min=0;
        Fixed the left digit for
        (int i=0; i<a.length-1;i++) {
            min = i;
            Find the lowest value for
            (int j=i+1;j<a.length;j++) {

                 if (A[min]>a[j]) {
                     min = j}
            }
           after subscript I start Ensure a stable sort with values equal without swapping
            if (i!=min) {
                swap (a,i,min);
            }

        return A;

    }

    Arrays are passed by reference, changing arrays in functions
    private void Swap (int[] A,int i,int j) {
        int temp = a[i];
        A[i] = a[j];
        A[J] = temp;
    }

}

(c).? Direct Insert Sort

"topic" For an int array, write an insert sort algorithm that sorts the array elements.
Given an int array A and the size n of the array, return the sorted array.

Import java.util.*;

public class Insertionsort {public
    int[] Insertionsort (int[] A, int n) {
      ///Insert Poker with the thought
        //inserted playing card
        int i,j , temp;
        You have inserted a sheet, continue inserting for
        (i=1;i<n;i++) {

            temp = a[i];
            Move back one of the cards in front of I that is larger than the card you want to insert, and empty out a new card for
            (j=i;j>0&&a[j-1]>temp;j--) {
                a[j] = a[j-1];
            }
            The empty one fills the inserted card
            a[j] = temp;

        }
        return A;


    }
}

(iv).? Hill sort

"topic" For an int array, write a hill sort algorithm that sorts the array elements.
Given an int array A and the size n of the array, return the sorted array. Guaranteed element is less than or equal to 2000.

The basic idea: the algorithm first sets the number of groups to be sorted by an increment D (n/2,n to the number of sorted numbers) into several groups, the subscript of a record in each group D. Inserts a direct sort of all elements in each group, then groups it with a smaller increment (D/2), and then inserts the sort directly in each group. When the increment is reduced to 1 o'clock, the sort completes after a direct insert sort.

The hill Sort method (narrowing increment method) is a sort of insertion class, which is the method of inserting the whole sequence of sequences into several small subsequence.

Import java.util.*;

public class Shellsort {public
    int[] Shellsort (int[] A, int n) {
        //card
        int temp,j,i to insert;
        Set Delta D, incremental D/2 gradually decrease for
        (int D = N/2;D>=1;D=D/2) {

            //start with subscript D, insert sort on Group D for
            (j=d;j<n;j++) {

                temp = a[ j];
                for (I=j;i>=d&&a[i-d]>temp;i-=d) {
                    a[i]=a[i-d];
                }

                A[i]=temp
            }

        }

        return A;
    }
}

(? v.).? Heap Sort

"topic" For an int array, write a heap sort algorithm that sorts the array elements.
Given an int array A and the size n of the array, return the sorted array. "Heap" 1. Heap is a complete binary tree 2. Large Top heap: The value of each node is greater than or equal to the value of its left and right child nodes, known as the large top heap. 3. Small top heap: The value of each node is greater than or equal to its left and right child nodes, known as the small top heap. "Complete Binary Tree Property 5": If i>1, then the parent is the node [I/2]. That is to say subscript I and 2i and 2i+1 are parent-child relationships. When a sort object is an array, the subscript starts at 0, so subscript i is a parent-child relationship with subscript 2i+1 and 2i+2.

Import java.util.*;
        public class Heapsort {public int[] Heapsort (int[] A, int n) {//heap sort algorithm int i;
        First the a[] array is constructed into a large top heap.
        Starting from the lowest and rightmost nodes of the complete binary tree.
        for (i=n/2-1;i>=0;i--) {heapadjust (a,i,n);
            //Start traversal for (i=n-1;i>0;i--) {swap (a,0,i);
        Get a maximum value per Exchange and discard heapadjust (a,0,i);

    return A;
        }//a[i] Represents the root node of subscript I, private void Heapadjust (int[] a,int i,int N) {//"note" here subscript starting from 0 int temp;
        Storage root Node temp = A[i]; Traversing the larger down of the left and right children of the root node, because of the complete binary tree characteristic I of the left sub node of 2i+1 I, 2i+2 for (int j=2*i+1;j<n;j=j*2+1) {if (J<n-1&amp
            ; &a[j]<a[j+1]) {++j;
            } if (Temp>=a[j]) {break;
            ///Assign the child nodes to the root node a[i] = A[j];
        Assigning sub node subscript to i = j;

    (Assign the value of the stored root node to the child node a[i] = temp; } Private void Swap (int[] A,int i,int j) {int temp = A[i];
        A[I]=A[J];

    A[J] = temp; }
}

(vi). Merge sort algorithm

"topic" For an int array, write a merge sort algorithm that sorts the array elements.
Given an int array A and the size n of the array, return the sorted array. First, the recursive method, the default sorting method is 2-way merge sort. Look at this picture should be able to immediately understand:
Order each subsequence first, and then merge the two sorted sequences into one sequence of operations. If the two ordered table is merged into an ordered table, it is called two-way merge.

Import java.util.*;
        public class MergeSort {public int[] mergesort (int[] A, int n) {//merge sort, recursive procedure, Divide and conquer Msort (a,0,n-1);
    return A;
            } private void Msort (int[] A,int left,int right) {//Divide and conquer, recursive common thought, jump out of the recursive condition if (left>=right) {
        Return
        //Midpoint int mid = (left+right)/2;
        Somewhat similar to the subsequent traversal.
        Msort (A,left,mid);

        Msort (A,mid+1,right);



    Merge (A,left,mid,right); ///Arrange sequence sequences of the left and right groups into sequence private void merge (int[] a,int left,int mid,int rightend) {//act as subscript in the TEM array
        T record = left;
        Use int record2 = left when the array is last copied;
        Start subscript int m =mid+1 of the right sub sequence;

        int[] tem = new Int[a.length]; As long as Left>mid or m>rightend, jump out of the loop while (Left<=mid&&m<=rightend) {if (a[left]<=a[m)
            ) {tem[record++]=a[left++];
            }else{tem[record++]=a[m++];
   }

        }     while (Left<=mid) {tem[record++]=a[left++];
        while (M<=rightend) {tem[record++]=a[m++];
        ///copy array for (; record2<=rightend;record2++) {A[record2] = Tem[record2];
 }

    }

}

(?? Seven).?? Fast sorting algorithm

"topic" For an int array, write a quick sort algorithm that sorts the array elements.
Given an int array A and the size n of the array, return the sorted array.

"Basic idea": Quick sort (Quicksort) is an improvement to bubble sorting, using the partition method (Divide and conquer) strategy to divide a sequence (list) into two subsequence (sub-lists).

The "step" is to pick an element from the sequence called a "pivot" (pivot). Reorder the columns, all elements are smaller than the pivot values, and all elements are larger than the pivot values behind the pivot (the same number can be on either side). After the partition is finished, the pivot is in the middle of the sequence. This is called a partition (partition) operation. recursively (recursive) sorts the subsequence smaller than the pivot value element and the subsequence larger than the pivot value element.

Import java.util.*;

        public class QuickSort {public int[] QuickSort (int[] A, int n) {//Quick sort qsort (a,0,n-1);

    return A;
        } public void Qsort (int[] A,int left,int right) {//pivot int pivot;

            if (left<right) {pivot = partition (a,left,right);
            Qsort (a,left,pivot-1);

        Qsort (A,pivot+1,right);

        }//Optimization Select a pivot, try to put it in a position, make it to the left of the value is smaller than it, the value on the right than it large public int partition (int[] A,int left,int rights) {
        Optimal selection of pivot, using the method of the three-count PivotKey = MEDIAN3 (a,left,right); Alternately from the two sides of the table to the intermediate scan/pivot is backed up with PivotKey while (Left<right) {while (Left<right&&a[right]&gt
           ; =pivotkey) {right--;
           ///Replace mode, because pivot to back up, one more storage space a[left]=a[right];
           while (Left<right&&a[left]<=pivotkey) {left++;

        } A[right]=a[left];
  //Put the pivot in its real place      A[left]=pivotkey;
    return to left;
        ///Three count public int median3 (int[] A,int left,int right) {int mid= (right-left)/2;
        if (A[left]>a[right]) {swap (a,left,right);
        } if (A[mid]>a[left]) {swap (a,mid,left);
        } if (A[mid]>a[right]) {swap (a,mid,right);
    return A[left];
        public void Swap (int[] A,int i,int j) {int temp =a[i];
        A[I]=A[J];
    A[j]=temp; }



}
"? Fast efficiency"

Time performance depends on the depth of recursion, and recursive tree can be used to describe the implementation of recursive algorithm. In the optimal case, partition each division evenly, sorted n values, then the depth of the recursive tree is [logn]+1, the first partition need to scan the entire array, do n times comparison, second to half scan. So the optimal time complexity of 0 (n log n), the worst time complexity 0 (n^2), the average time complexity of 0 (n log n).

Recursion results in the use of stack space, with the best spatial complexity of 0 (log n), and the worst spatial complexity 0 (N).

(?? VIII).?? Bucket sorting algorithm
The bucket sort step sets a quantitative array as an empty bucket. Search the sequence and put the item one at a corresponding bucket. Sort each bucket that is not empty. From the empty bucket, put the item back into the original sequence.

(?? ix).?? Count sort algorithm (in fact, bucket sort algorithm)

Characteristics
1. In advance, it must be known that the keyword to be sorted is an integral type and the range is known.
2. Time complexity is O (n+k), n refers to the number of barrels, k refers to the length of the array to be sorted, not based on the comparison of the sorting algorithm, so the efficiency is very high.
3. The stability is good, this is the count sorts very important characteristic, may use in later introduction's cardinal order.
4. But some auxiliary arrays are needed, such as C[0..K], so the keyword range to be sorted 0~k not be too large.

Import java.util.*;

public class Countingsort {public
    int[] Countingsort (int[] A, int n) {
        if (A==null | | N<2) {return
            A;
        }
        Find the bucket range, that is, to determine the bucket range int Min=a[0] by the maximum minimum value of the array to be sorted
        ;
        int max=a[0];
        for (int i=0;i<n;i++) {
            min=math.min (a[i],min);
            Max=math.max (A[i],max);
        }
        To determine the bucket array, the bucket's subscript is the value to sort the array, and the bucket's value is ordinal sort number of times the same set of values appears
        int[] arr = new int[max-min+1];
        Allocate element for
        (int i=0;i<n;i++) {
            arr[a[i]-min]++
        }

        to Bucket Remove the element int index=0 from the bucket
        ;
        for (int i=0;i<arr.length;i++) {while
            (arr[i]-->0) {
                a[index++]=i+min
            }
        }

        return A;
    }
}

(?? Ten).??? Cardinality sorting algorithm (based on bucket sort)

The principle cardinality sort (radix sort) is a non-comparison integer sort algorithm that cuts integers by bits to different numbers, and then compares them by each number of digits. Because integers can also express strings (such as names or dates) and floating-point numbers in a particular format, cardinality sorting is not only used for integers.

Unify all values to be compared (positive integers) to the same number of digits, preceded by a short number of 0. Then, start at the lowest bit, and then sort it one at a time. This is done from the lowest bit to the highest order, and the sequence becomes an ordered series.

"topic" for an array of int, write a cardinal sort algorithm that sorts the array elements.
Given an int array A and the size n of the array, return the sorted array. Guaranteed elements are less than or equal to 2000.

Import java.util.*;
Import Java.lang.Math; public class Radixsort {public int[] Radixsort (int[] A, int n) {//base sort based on bucket//To determine the number of trips to sort, that is, the maximum value in the sorted array is 80
        9 o'clock, the number of trips is 3 int max=a[0];
            for (int i=0;i<n;i++) {if (A[i]>max) {max= a[i];
        }//Calculate Max's bit int time=0;
            while (max>0) {max/=10;
        time++; }//"Bucket" Initializes 10 linked list as bucket, arraylist<arraylist<integer>> list = new Arraylist<arraylist<i when user assigns
        Nteger>> ();
            for (int i=0;i<10;i++) {arraylist<integer> Item = new arraylist<integer> ();
        List.add (Item); //Time allocation and collection for (int i=0;i<time;i++) {//allocation element, in order precedence, starting with single-digit for (int j=0;j&
                lt;n;j++) {int index = a[j]% (int) Math.pow (10,i+1)/(int) Math.pow (10,i);
            List.get (Index). Add (A[j]); }//Collect elements, one by one bucketset int count=0;

                    10 bucket for (int k=0;k<10;k++) {//Bucket collection if (List.get (k). Size () >0) {
                        for (int a:list.get (k)) {a[count]=a;   
                    count++;
                //Purge data for next collection of List.get (k). Clear (); 
    }} return A; }
}
"? Base sorting efficiency"

The time complexity of cardinality ordering is O (k n), where n is the number of sorted elements, and K is the number of digits. Note that this is not to say that this time complexity must be better than O (n log (n)), the size of K depends on the selection of digits and the size of the complete set of data types to which the data is to be sorted; K determines how many rounds are processed, and N is the number of operations per round

Cardinal Sort basic operation cost is small, k is generally not logn, so cardinal order usually faster than based on comparison of sort, such as quick sort.

The worst space complexity is O (k N)

Finally, I strongly introduce this blog, I was sorting out the blog to find this blog, explain profound, easy to understand: http://blog.csdn.net/amazing7/article/details/51603682

This blog for algorithmic motion diagram understanding: http://blog.jobbole.com/11745/

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.