Common sorting methods in java

Source: Internet
Author: User
Tags rounds

Copy codeThe Code is as follows: package com. test;

Import java. util. Random;

/**
* Sorting Test class
*
* Sorting algorithms are classified as follows: 1. Insert sorting (insert sorting, semi-insert sorting, and Hill sorting); 2. Exchange sorting (Bubble sorting and fast sorting );
* 3. Select sorting (directly select sorting and heap sorting); 4. Merge Sorting; 5. Base sorting.
*
* About sorting method selection: (1) if n is small (for example, n ≤ 50), you can directly insert or directly select sorting.
* When the record size is small, the direct insertion sorting is better; otherwise, the sorting should be selected because the number of records to be moved is less than the direct insertion.
* (2) if the initial state of the file is basically ordered (in positive order), it is appropriate to directly insert, bubble, or randomly sort the file quickly;
* (3) if n is large, the time complexity is O (nlgn.
*
*/

Public class Sort {
/**
* Method of initializing the test Array
*
* @ Return an initialized Array
*/
Public int [] createArray (){
Random random = new Random ();
Int [] array = new int [10];
For (int I = 0; I <10; I ++ ){
Array [I] = random. nextInt (100)-random. nextInt (100); // generate two random numbers to subtract from each other to ensure a negative number in the generated number
}
System. out. println ("=========== original sequence ========= ");
PrintArray (array );
Return array;
}

/**
* Print the elements in the array to the console.
*
* @ Param source
*/
Public void printArray (int [] data ){
For (int I: data ){
System. out. print (I + "");
}
System. out. println ();
}

/**
* Swap the positions of the specified two elements in the array
*
* @ Param data
* @ Param x
* @ Param y
*/
Private void swap (int [] data, int x, int y ){
Int temp = data [x];
Data [x] = data [y];
Data [y] = temp;
}

/**
* Bubble Sorting-exchange sorting
* Method: compare two adjacent elements. If necessary, exchange them. The maximum elements are placed at the end of each loop (for example, ascending order ), the next cycle is to perform similar operations on other numbers.
* Performance: number of comparisons O (n ^ 2), n ^ 2/2, number of exchanges O (n ^ 2), n ^ 2/4
*
* @ Param data
* Array to be sorted
* @ Param sortType
* Sorting type
* @ Return
*/
Public void bubbleSort (int [] data, String sortType ){
If (sortType. equals ("asc") {// Positive Sorting, from small to large
// Number of rounds to be compared
For (int I = 1; I <data. length; I ++ ){
// Compare two adjacent numbers, and bubble after a large number
For (int j = 0; j <data. length-I; j ++ ){
If (data [j]> data [j + 1]) {
// Swap two adjacent numbers
Swap (data, j, j + 1 );
}
}
}
} Else if (sortType. equals ("desc") {// reverse sorting, from large to small
// Number of rounds to be compared
For (int I = 1; I <data. length; I ++ ){
// Compare two adjacent numbers, and bubble after a large number
For (int j = 0; j <data. length-I; j ++ ){
If (data [j] <data [j + 1]) {
// Swap two adjacent numbers
Swap (data, j, j + 1 );
}
}
}
} Else {
System. out. println ("the sorting type you entered is incorrect! ");
}
PrintArray (data); // outputs the array values after the Bubble sorting.
}

/**
* Directly select sorting method ---- select a sorting method
* Method: select the smallest (or largest) element from the data elements to be sorted in sequence at the end of the sorted series, until all data elements to be sorted are arranged.
* Performance: number of comparisons O (n ^ 2), n ^ 2/2
* Number of exchanges O (n), n
* The number of exchanges is much less than that of Bubble sorting. Because the CPU time required for switching is much longer than the CUP time required, the sorting is faster than Bubble sorting.
* However, when N is large, the CPU time required is dominant. Therefore, the performance and Bubble sorting are not much different, but it must be faster without a doubt.
*
* @ Param data
* Array to be sorted
* @ Param sortType
* Sorting type
* @ Return
*
*/
Public void selectSort (int [] data, String sortType ){
If (sortType. equals ("asc") {// Positive Sorting, from small to large
Int index;
For (int I = 1; I <data. length; I ++ ){
Index = 0;
For (int j = 1; j <= data. length-I; j ++ ){
If (data [j]> data [index]) {
Index = j;
}
}
// Switch the data. length-I and index (maximum value) in the position
Swap (data, data. length-I, index );
}
} Else if (sortType. equals ("desc") {// reverse sorting, from large to small
Int index;
For (int I = 1; I <data. length; I ++ ){
Index = 0;
For (int j = 1; j <= data. length-I; j ++ ){
If (data [j] <data [index]) {
Index = j;
}
}
// Switch the data. length-I and index (maximum value) in the position
Swap (data, data. length-I, index );
}
} Else {
System. out. println ("the sorting type you entered is incorrect! ");
}
PrintArray (data); // The output selects the sorted array value directly.
}

/**
*
* Insert sorting
*
* Method: Insert a record to an ordered table (possibly an empty table) in the sorted order to obtain an ordered table with a new number of records increasing by 1.
* Performance: number of comparisons O (n ^ 2), n ^ 2/4
* Number of copies O (n), n ^ 2/4
* The number of comparisons is the average of the first two, while the CPU time required for replication is less than exchanged, so the performance is more than doubled than the Bubble sorting, and faster than the selected sorting.
*
* @ Param data
* Array to be sorted
* @ Param sortType
* Sorting type
*/
Public void insertSort (int [] data, String sortType ){
If (sortType. equals ("asc") {// Positive Sorting, from small to large
// Number of rounds to be compared
For (int I = 1; I <data. length; I ++ ){
// Ensure that the first I + 1 count is sorted
For (int j = 0; j <I; j ++ ){
If (data [j]> data [I]) {
// Switch the number of j and I in the position
Swap (data, I, j );
}
}
}
} Else if (sortType. equals ("desc") {// reverse sorting, from large to small
// Number of rounds to be compared
For (int I = 1; I <data. length; I ++ ){
// Ensure that the first I + 1 count is sorted
For (int j = 0; j <I; j ++ ){
If (data [j] <data [I]) {
// Switch the number of j and I in the position
Swap (data, I, j );
}
}
}
} Else {
System. out. println ("the sorting type you entered is incorrect! ");
}
PrintArray (data); // output the inserted sorted array values
}

/**
*
* Reverse Array Method
*
* @ Param data
* Source Array
*/
Public void reverse (int [] data ){
Int length = data. length;
Int temp = 0; // Temporary Variable
For (int I = 0; I <length/2; I ++ ){
Temp = data [I];
Data [I] = data [length-1-I];
Data [length-1-I] = temp;
}
PrintArray (data); // output to the converted array value
}

/**
*
* Fast sorting
*
* The Divide and conquer policy is used to Divide a sequence (list) into two subsequences (sub-lists ).
*
* Steps:
* 1. Pick out an element from the sequence, which is called a benchmark ),
* 2. Re-sort the series. All elements are placed before the benchmark values smaller than the benchmark values, and all elements are placed behind the benchmark values larger than the benchmark values (the same number can reach either side ). After this split, the benchmark is its final position. This is called a partition operation.
* 3. recursively sort the subseries smaller than the reference value element and the subseries greater than the reference value element.
*
* At the bottom of the delivery, the number of rows is zero or one, that is, they are always sorted. Although it is always handed back, this algorithm always ends, because in each iteration, it will at least place an element at its final position.
*
* @ Param data
* Array to be sorted
* @ Param low
* @ Param high
* @ See SortTest # qsort (int [], int, int)
* @ See SortTest # qsort_desc (int [], int, int)
*
*/
Public void quickSort (int [] data, String sortType ){
If (sortType. equals ("asc") {// Positive Sorting, from small to large
Qsort_asc (data, 0, data. length-1 );
} Else if (sortType. equals ("desc") {// reverse sorting, from large to small
Qsort_desc (data, 0, data. length-1 );
} Else {
System. out. println ("the sorting type you entered is incorrect! ");
}
}

/**
*
* Specific implementation of fast sorting, sorting in positive order
*
* @ Param data
* @ Param low
* @ Param high
*/
Private void qsort_asc (int data [], int low, int high ){
Int I, j, x;
If (low I = low;
J = high;
X = data [I];
While (I <j ){
While (I <j & data [j]> x ){
J --; // find the first number less than x from the right to the left
}
If (I <j ){
Data [I] = data [j];
I ++;
}
While (I <j & data [I] <x ){
I ++; // find the first number greater than x from left to right
}
If (I <j ){
Data [j] = data [I];
J --;
}
}
Data [I] = x;
Qsort_asc (data, low, I-1 );
Qsort_asc (data, I + 1, high );
}
}

/**
*
* Specific implementation of quick sorting and reverse sorting
*
* @ Param data
* @ Param low
* @ Param high
*
*/
Private void qsort_desc (int data [], int low, int high ){
Int I, j, x;
If (low I = low;
J = high;
X = data [I];
While (I <j ){
While (I <j & data [j] <x ){
J --; // find the first number less than x from the right to the left
}
If (I <j ){
Data [I] = data [j];
I ++;
}
While (I <j & data [I]> x ){
I ++; // find the first number greater than x from left to right
}
If (I <j ){
Data [j] = data [I];
J --;
}
}
Data [I] = x;
Qsort_desc (data, low, I-1 );
Qsort_desc (data, I + 1, high );
}
}

/**
*
* Binary search for the position of a specific integer in an integer array (recursion)
*
* The query for a linear table must be an ordered list.
*
* @ Paramdataset
* @ Paramdata
* @ ParambeginIndex
* @ ParamendIndex
* @ Returnindex
*
*/
Public int binarySearch (int [] dataset, int data, int beginIndex, int endIndex ){
Int midIndex = (beginIndex + endIndex) >>> 1; // equivalent to mid = (low + high)
/// 2, but the efficiency will be higher
If (data <dataset [beginIndex] | data> dataset [endIndex] | beginIndex> endIndex)
Return-1;
If (data <dataset [midIndex]) {
Return binarySearch (dataset, data, beginIndex, midIndex-1 );
} Else if (data> dataset [midIndex]) {
Return binarySearch (dataset, data, midIndex + 1, endIndex );
} Else {
Return midIndex;
}
}

/**
*
* Binary search for the position of a specific integer in an integer array (non-recursive)
*
* The query for a linear table must be an ordered list.
*
* @ Paramdataset
* @ Paramdata
* @ Returnindex
*
*/
Public int binarySearch (int [] dataset, int data ){
Int beginIndex = 0;
Int endIndex = dataset. length-1;
Int midIndex =-1;
If (data <dataset [beginIndex] | data> dataset [endIndex] | beginIndex> endIndex)
Return-1;
While (beginIndex <= endIndex ){
MidIndex = (beginIndex + endIndex) >>> 1; // equivalent to midIndex =
// (BeginIndex +
// EndIndex)/2, but the efficiency is higher
If (data <dataset [midIndex]) {
EndIndex = midIndex-1;
} Else if (data> dataset [midIndex]) {
BeginIndex = midIndex + 1;
} Else {
Return midIndex;
}
}
Return-1;
}

Public static void main (String [] args ){

Sort sortTest = new Sort ();

Int [] array = sortTest. createArray ();
System. out. println ("=========== after the Bubble Sorting (positive order) =========== ");
SortTest. bubbleSort (array, "asc ");
System. out. println ("=========== after the Bubble Sorting (reverse) ============= ");
SortTest. bubbleSort (array, "desc ");

Array = sortTest. createArray ();
System. out. println ("=========== after reversing the array =========== ");
SortTest. reverse (array );

Array = sortTest. createArray ();
System. out. println ("============= select the sort (forward) ============= ");
SortTest. selectSort (array, "asc ");
System. out. println ("============= select the sort (reverse) ============= ");
SortTest. selectSort (array, "desc ");

Array = sortTest. createArray ();
System. out. println ("=========== after insertion (positive order) =========== ");
SortTest. insertSort (array, "asc ");
System. out. println ("=========== after insertion (inverted) =========== ");
SortTest. insertSort (array, "desc ");

Array = sortTest. createArray ();
System. out. println ("=========== after fast sorting (positive order) =========== ");
SortTest. quickSort (array, "asc ");
SortTest. printArray (array );
System. out. println ("=========== after fast sorting (reverse) ============= ");
SortTest. quickSort (array, "desc ");
SortTest. printArray (array );

System. out. println ("=========== array Binary Search ========= ");
System. out. println ("The number you are looking for is in the" + sortTest. binarySearch (array, 74)

+ "Seats. (Subscript is calculated from 0 )");
}
}

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.