Java implementation of several common sorting algorithm code _java

Source: Internet
Author: User
Tags comparable comparison

Stability (stability)
A sort algorithm is stable, when there are two equal records of the keywords R and S, and in the original list R appears before s, in the sorted list, R will also be before S.

Sorting algorithm classification

Common inserts (insert sort/hill Sort), swap (bubble sort/quick Sort), select (select Sort), merge (merging sort), etc.

I. Insert Sort

Insert sort (insertion sort), which works by building an ordered sequence, scanning the sorted sequence for unsorted data, and then moving forward from the back, finding the location and inserting it. Insert sorting on implementation, usually using in-place sorting (that is, just use the extra space of O (1) to sort), and in the process of backward scanning, you need to repeatedly move the sorted elements backwards and forwards, providing insert space for the newest elements.

In general, the insertion sort is implemented on an array using In-place. The specific algorithm is described as follows:

Starting with the first element, the element can be thought to have been sorted.
Takes out the next element and scans backwards in the sorted sequence of elements.
If the element (sorted) is greater than the new element, move the element to the next position.
Repeat step 3 until you find the position where the sorted element is less than or equal to the new element.
Inserts a new element after the location.
Repeat steps 2~5.

Copy Code code as follows:



public static void Insertionsort (int[] data) {


for (int index = 1; index < data.length; index++) {


int key = Data[index];


int position = index;


Shift larger values to the right


while (Position > 0 && data[position-1] > key) {


Data[position] = data[position-1];


position--;


}


Data[position] = key;


}


}





two. Hill sort

Hill sort (Shell sort) is a sort of insertion. is for the improvement of the direct insertion sort algorithm. The method is also called narrowing the incremental order, due to DL. The shell was named after it was introduced in 1959.

The hill sort is based on the following two-point nature of the insertion order:

The insertion sort is efficient in the operation of data that is almost already sorted out, that is, the efficiency of linear sorting can be achieved.
However, the insertion sort is generally inefficient because the insertion sort can only move data one bit at a time.

Copy Code code as follows:

static <e extends Comparable<? Super e>> void Shellsort (list<e> a) {
int h = 1;
while (H < a.size ()/3) H = h*3 + 1; <o (n^ (3/2)) by Knuth,1973>: 1, 4, 13, 40, 121, ...
for (; H >= 1; H/= 3)
for (int i = h; i < a.size (); i++)
for (int j = i; J >= H && A.get (j). CompareTo (A.get (j-h)) < 0; j-=h)
Collections.swap (A, J, j-h);
}



three. Bubble sort

Bubble sort (Bubble sort, Taiwan translation: bubble sort or bubble sort) is a simple sorting 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.

The bubble sort algorithm works as follows:

Compare adjacent elements, if the first one is larger than the second, swap them both.
For each pair of adjacent elements to do the same work, from the beginning of the first pair to the end of the last pair, at this point, the final 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.

Copy Code code as follows:



public static void Bubblesort (int[] data) {


int temp = 0;


for (int i = data.length-1 i &gt; 0; i.) {


Boolean issort = false;


for (int j = 0; J &lt; i; ++j) {


if (Data[j + 1] &lt; Data[j]) {


temp = Data[j];


DATA[J] = data[j + 1];


Data[j + 1] = temp;


Issort = true;


}


}





If an exchange occurs in an internal loop, the comparison continues, and if no exchange occurs in an internal loop, it is considered sorted.


if (!issort)


Break


}


}





four. Quick Sort

The quick sort (Quicksort) is an improvement on bubble sorting. by C. A. R. Hoare was introduced in 1962. Its basic idea is to divide the data to be sorted into two separate parts by a sort of a part of all the data is smaller than the other part of all the data, and then the two parts of the data for the rapid sorting, the entire sequencing process can be recursive, so as to achieve the entire data into an ordered sequence.

The quick sort uses the divide-and-conquer method (Divide and conquer) policy to divide a serial (list) into two sub serial (sub-lists).

Steps are:

Pick an element from a sequence called a "datum" (pivot).
Reorder the series, all elements smaller than the base value placed in front of the datum, all elements are larger than the base value behind the datum (the same number can be on either side). After the partition exits, the datum is positioned in the middle of the series. This is called a partition (partition) operation.
recursively (recursive) sorts the substrings that are less than the datum elements and those that are larger than the datum values.

Copy Code code as follows:



/*


* More efficient implements for quicksort. &lt;br/&gt;


* Use left, center and right median value (@see #median ()) for the pivot, and


* The more efficient inner loop for the core of the algorithm.


*/


public class Quicksort {

public static final int CUTOFF = 11;

   /**
     * Quick sort algorithm. <br/>
      *
     * @param arr An array of comparable items <br/>
     */
    public static <t extends comparable< Super t>> void Quicksort (t[] arr) {
 & nbsp;      QuickSort (arr, 0, arr.length-1);
   }

/**
* Get the median, center and right. <br/>
* Order this and hide the pivot by put it's the end of the array. <br/>
*
* @param arr An array of comparable items. <br/>
* @param left the Most-left index of the subarray. <br/>
* @param right The most-right index of the subarray.<br/>
* @return T
*/
public static <t extends Comparable<? Super t>> T median (t[] arr, int left, int right) {

int center = (left + right)/2;

if (Arr[left].compareto (Arr[center]) > 0)
Swapref (arr, left, center);
if (Arr[left].compareto (Arr[right]) > 0)
Swapref (arr, left, right);
if (Arr[center].compareto (Arr[right]) > 0)
Swapref (arr, center, right);

Swapref (arr, center, right-1);
return arr[right-1];
}

/**
* Internal to sort the array with quick sort algorithm. <br/>
*
* @param arr An array of comparable Items. <br/>
* @param left the left-most index of the subarray. <br/>
* @param right The right-most index of the subarray. <br/>
*/
private static <t extends Comparable<? Super t>> void QuickSort (t[] arr, int left, int right) {
if (left + CUTOFF <= right) {
Find the Pivot
T pivot = median (arr, left, right);

Start partitioning


int i = left, j = right-1;


for (;;) {


while (Arr[++i].compareto (pivot) &lt; 0);


while (Arr[--j].compareto (pivot) &gt; 0);


if (I &lt; J)


Swapref (arr, I, j);


Else


Break


}

Swap the pivot reference back to the small collection.
Swapref (arr, I, right-1);

QuickSort (arr, left, i-1); Sort the small collection.
QuickSort (arr, i + 1, right); Sort the large collection.

       } else {
            /If the total number is less than CUTOFF we-use insertion sort
        ;    //instead (cause it more efficient).
            Insertionsort (arr, left, right);
       }
   }

/**
* method to swap references in a array.<br/>
*
* @param arr an array of Objects. <br/>
* @param idx1 The index of the "the". <br/>
* @param idx2 The index of the second element. <br/>
*/
public static <T> void Swapref (t[] arr, int idx1, int idx2) {
T tmp = arr[idx1];
ARR[IDX1] = arr[idx2];
ARR[IDX2] = tmp;
}

/**


* method to sort a subarray from start to end with insertion sort


* Algorithm. &lt;br/&gt;


*


* @param arr An array of comparable items. &lt;br/&gt;


* @param start the begining position. &lt;br/&gt;


* @param end position. &lt;br/&gt;


*/


public static &lt;t extends Comparable&lt;? Super t&gt;&gt; void Insertionsort (t[] arr, int start, int end) {


int i;


for (int j = start + 1; J &lt;= End; J + +) {


T tmp = Arr[j];


for (i = j; i &gt; Start &amp;&amp; tmp.compareto (arr[i-1]) &lt; 0; i--) {


Arr[i] = arr[i-1];


}


Arr[i] = tmp;


}


}

private static void PrintArray (integer[] c) {
for (int i = 0; i < c.length; i++)
System.out.print (C[i] + ",");

System.out.println ();
}

public static void Main (string[] args) {
integer[] data = {10, 4, 9, 23, 1, 45, 27, 5, 2};

System.out.println ("Bubblesort ...");
PrintArray (data);
Quicksort (data);
PrintArray (data);
}
}




five. Select Sort

Select sort (Selection sort) is a simple and intuitive sort algorithm. Its working principle is as follows. The smallest (Large) element is first found in the unordered sequence, placed at the start of the sort sequence, and then continues to look for the smallest (large) element from the remaining unsorted elements and then to the end of the sorted sequence. And so on until all the elements are sorted.

Because each trip to determine the elements of the process will have a selection of the minimum value of the sub-process, so people are called the choice of sorting.

For example, the sequence 5 8 5 2 9, we know that the first time to select the 1th element 5 will be exchanged with 2, then the original sequence 2 5 of the relative order is destroyed, so the selection is not a stable sorting algorithm.

Copy Code code as follows:



public static void Selectsort (int[] data) {


int minindex = 0;


int temp = 0;


for (int i = 0; i &lt; data.length; i++) {


Minindex = i; Minimum data array subscript for unordered area


for (int j = i + 1; j &lt; Data.length; J + +) {//Find the smallest data in the unordered area and save its array subscript


if (Data[j] &lt; Data[minindex]) {


Minindex = j;


}


}


if (Minindex!= i) {//If the minimum position of the unordered area is not the default first data, swap.


temp = Data[i];


Data[i] = Data[minindex];


Data[minindex] = temp;


}


}


}





Six. Merge sort

Merge sort is an efficient sorting algorithm based on merging operations. The algorithm is a very typical application of the partition method (Divide and Conquer).

The process of merging operations is as follows:

The application space is sized to the sum of two sorted sequences that are used to store the merged sequence.
Set two pointers, initially at the starting position of two sorted sequences.
Compares the elements pointed to by two pointers, selects the relatively small elements into the merged space, and moves the pointer to the next position.
Repeat step 3 until a pointer reaches the end of the sequence.
Copies all remaining elements of another sequence directly to the end of the merge sequence.

Copy Code code as follows:



public static int[] MergeSort (int[] arr) {//merge sort--recursive


if (arr.length = = 1) {


return arr;


}


int half = ARR.LENGTH/2;


int[] arr1 = new Int[half];


int[] arr2 = new Int[arr.length-half];


System.arraycopy (arr, 0, arr1, 0, arr1.length);


System.arraycopy (arr, half, arr2, 0, arr2.length);


arr1 = MergeSort (arr1);


ARR2 = MergeSort (ARR2);


Return Mergesortsub (arr1, ARR2);


}

private static int[] Mergesortsub (int[] arr1, int[] arr2) {//merge sort subroutine


Int[] result = new Int[arr1.length + arr2.length];


int i = 0;


int j = 0;


int k = 0;


while (true) {


if (Arr1[i] &lt; arr2[j]) {


RESULT[K] = Arr1[i];


if (++i &gt; Arr1.length-1) {


Break


}


} else {


RESULT[K] = Arr2[j];


if (++j &gt; Arr2.length-1) {


Break


}


}


k++;


}


for (; i &lt; arr1.length; i++) {


RESULT[++K] = Arr1[i];


}


for (; J &lt; Arr2.length; J + +) {


RESULT[++K] = Arr2[j];


}


return result;


}





Complete code (except Quicksort)


Copy Code code as follows:



Package com.clzhang.sample.thinking;

Import java.util.*;

/**


* Several common algorithms Java implementation of sorting algorithm


* @author Acer


*


*/


public class Commonsort {


/**


* Insert sort specific algorithm described below:


* 1. Starting with the first element, the element can be considered to have been sorted


* 2. Remove the next element and scan forward from the back in the sorted sequence of elements


* 3. If the element (sorted) is greater than the new element, move the element to the next position


* 4. Repeat step 3 until you find the sorted element is less than or equal to the new element's position


* 5. After inserting the new element into the location


* 6. Repeat steps 2~5


*/


public static void Insertionsort (int[] data) {


for (int index = 1; index &lt; data.length; index++) {


int key = Data[index];


int position = index;


Shift larger values to the right


while (Position &gt; 0 &amp;&amp; data[position-1] &gt; key) {


Data[position] = data[position-1];


position--;


}


Data[position] = key;


}


}





/**


* Hill sort, algorithm to realize the idea of Wikipedia; suitable for a large number of sorting operations.


*/


static &lt;e extends Comparable&lt;? Super e&gt;&gt; void Shellsort (list&lt;e&gt; a) {


int h = 1;


while (H &lt; a.size ()/3) H = h*3 + 1; &lt;o (n^ (3/2)) by Knuth,1973&gt;: 1, 4, 13, 40, 121, ...


for (; H &gt;= 1; H/= 3)


for (int i = h; i &lt; a.size (); i++)


for (int j = i; J &gt;= H &amp;&amp; A.get (j). CompareTo (A.get (j-h)) &lt; 0; j-=h)


Collections.swap (A, J, j-h);


}

/**


* The bubble sort algorithm works as follows:


* 1. Compare adjacent elements. If the first one is bigger than the second one, swap them both.


* 2. For each pair of adjacent elements to do the same work, from the beginning of the first pair to the end of the last pair. At this point, the final element should be the largest number.


* 3. Repeat the above steps for all elements except the last one.


* 4. Continue to repeat the above steps for fewer elements at a time, until no pair of digits need to be compared. [1]


*/


public static void Bubblesort (int[] data) {


int temp = 0;


for (int i = data.length-1 i &gt; 0; i.) {


Boolean issort = false;


for (int j = 0; J &lt; i; ++j) {


if (Data[j + 1] &lt; Data[j]) {


temp = Data[j];


DATA[J] = data[j + 1];


Data[j + 1] = temp;


Issort = true;


}


}





If an exchange occurs in an internal loop, the comparison continues, and if no exchange occurs in an internal loop, it is considered sorted.


if (!issort)


Break


}


}





/**


* The basic idea of choosing a sort is:


* 1. In the process of traversing an array, with I representing the sequence ordinal that is currently needed, you need to find the minimum value in the remaining [i+1...n-1].


* 2. Then the smallest value found is exchanged with the value I point to.


* Because each trip to determine the elements of the process will have a selection of the minimum value of the sub-process, so people are called the choice of sorting.


* @param data


*/


public static void Selectsort (int[] data) {


int minindex = 0;


int temp = 0;


for (int i = 0; i &lt; data.length; i++) {


Minindex = i; Minimum data array subscript for unordered area


for (int j = i + 1; j &lt; Data.length; J + +) {//Find the smallest data in the unordered area and save its array subscript


if (Data[j] &lt; Data[minindex]) {


Minindex = j;


}


}


if (Minindex!= i) {//If the minimum position of the unordered area is not the default first data, swap.


temp = Data[i];


Data[i] = Data[minindex];


Data[minindex] = temp;


}


}


}





/**


* The process of merging operations is as follows:


* 1. Application space so that its size is the sum of two sorted sequences, which are used to store the merged sequence


* 2. Set two pointers, initially at the beginning of two sorted sequences


* 3. Compare the elements pointed to by the two pointers, select the relatively small elements into the merged space, and move the pointer to the next position


* 4. Repeat step 3 until a pointer reaches the end of the sequence


* 5. Copy all remaining elements of another sequence directly to the end of the merge sequence


*/


public static int[] MergeSort (int[] arr) {//merge sort--recursive


if (arr.length = = 1) {


return arr;


}


int half = ARR.LENGTH/2;


int[] arr1 = new Int[half];


int[] arr2 = new Int[arr.length-half];


System.arraycopy (arr, 0, arr1, 0, arr1.length);


System.arraycopy (arr, half, arr2, 0, arr2.length);


arr1 = MergeSort (arr1);


ARR2 = MergeSort (ARR2);


Return Mergesortsub (arr1, ARR2);


}

private static int[] Mergesortsub (int[] arr1, int[] arr2) {//merge sort subroutine


Int[] result = new Int[arr1.length + arr2.length];


int i = 0;


int j = 0;


int k = 0;


while (true) {


if (Arr1[i] &lt; arr2[j]) {


RESULT[K] = Arr1[i];


if (++i &gt; Arr1.length-1) {


Break


}


} else {


RESULT[K] = Arr2[j];


if (++j &gt; Arr2.length-1) {


Break


}


}


k++;


}


for (; i &lt; arr1.length; i++) {


RESULT[++K] = Arr1[i];


}


for (; J &lt; Arr2.length; J + +) {


RESULT[++K] = Arr2[j];


}


return result;


}

private static void PrintArray (int[] c) {
for (int i = 0; i < c.length; i++)
System.out.print (C[i] + ",");

System.out.println ();
}

public static void Main (String []args) {
int[] data = {10,4,9,23,1,45,27,5,2};

System.out.println ("Bubblesort ...");
Int[] A = Data.clone ();
PrintArray (a);
Bubblesort (a);
PrintArray (a);

System.out.println ("Selectsort ...");
Int[] B = data.clone ();
PrintArray (b);
Selectsort (b);
PrintArray (b);

System.out.println ("Insertionsort ...");
Int[] C = data.clone ();
PrintArray (c);
Insertionsort (c);
PrintArray (c);

System.out.println ("Shellsort ...");
list<integer> list = new arraylist<integer> ();
for (int i=0;i<data.length;i++)
List.add (Data[i]);
SYSTEM.OUT.PRINTLN (list);
Shellsort (list);
SYSTEM.OUT.PRINTLN (list);

System.out.println ("MergeSort ...");
Int[] D = data.clone ();
PrintArray (d);
PrintArray (MergeSort (d));
}

}

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.