Sorting Algorithms in Java

Source: Internet
Author: User
Tags benchmark

In Java, sorting can be divided into internal sorting, the external sort is as follows:

Here we discuss select sort, bubble sort, quick sort

Select sort

In the set of numbers to be sorted, select the minimum (or maximum) number to exchange with the 1th position, and then in the remaining number, find the minimum (or maximum) number of the 2nd position to exchange, and so on, until the first N-1 element (the penultimate number) and the nth element (the last a single number) is compared.

Operation Method:

First trip, from N records to find the minimum key code record and the first record exchange;

Second, the second record from the beginning of the n-1 record to select the minimum key code record and the second record exchange;

And so on .....

On the first trip, the record with the smallest key code is selected from the N-i+1 record beginning with the first record, and the first record is exchanged,

Until the entire sequence is ordered by key code.

Package Com;public class Simpleselectsort {public static void main (string[] args) {int a[] = {3,1,5,7,2,4,9,6,10,8};  Simpleselectsort  obj=new simpleselectsort (); SYSTEM.OUT.PRINTLN ("Initial value:"); Obj.print (a); Obj.selectsort (a); System.out.println ("\ n sort after:"); Obj.print (a);} private void Selectsort (int[] a) {for (int i=0;i<a.length;i++) {int k=i;//k holds the lowest value subscript. The minimum value of each loop subscript +1for (int j=i+1;j<a.length;j++) {//Find the lowest value subscript if (a[k]>a[j]) k=j;} Swap (a,k,i);//Place the minimum value where it should be}}public void print (int a[]) {for (int i=0;i<a.length;i++) {System.out.print (a[i]+ "");}} Public  Void Swap (int[] data, int i, int j) {          if (i = = j) {              return;          }          Data[i] = Data[i] + data[j];          DATA[J] = Data[i]-data[j];          Data[i] = Data[i]-data[j];      }  }

Simple Selection sorting improvements

Simple selection of sorting, each loop can only determine the positioning of an element after sorting. We can consider improving the position of two elements (the current maximum and minimum records) for each cycle, thus reducing the number of cycles required for sorting. Improved to sort n data, up to [N/2] loop. The specific implementation is as follows:

Bubble sort

Basic idea:

In the set of numbers to be sorted, the total number in the range that is not currently in sequence, the top-down pairs of adjacent two numbers are compared and adjusted sequentially, so that the larger number to sink , smaller upward. That is, each time a comparison of two adjacent numbers finds that they are in the opposite order of order, they are interchanged.

Example of bubbling sort:

void Bubblesort (int a[], int n) {for      (int i =0; i< n-1; ++i) {for          (int j = 0; j < n-i-1; ++j) {              if (A[j] > a[j+1])              {                  int tmp = A[J]; A[j] = a[j+1];  A[J+1] = tmp;}}}}    

  

Improvement of bubble sorting algorithm

A common improvement on bubble sorting is to add a symbolic variable exchange, which is used to flag whether there is data exchange in a certain sort of trip, and if there is no data exchange during a certain trip, the data is arranged as required, and the sorting can be finished immediately, avoiding unnecessary comparisons. This article provides the following two improved algorithms:

1. Set up a symbolic variable pos, which records the position of the last interchange in the order of each trip. Since the POS location after the record has been exchanged in place, so in the next sequencing as long as the scan to POS location.

The improved algorithm is as follows:

void bubble_1 (int r[], int n) {      int i= n-1;  Initially, the last position remains the same while      (i> 0) {           int pos= 0;//At the beginning of each trip, no record interchange for          (int j= 0; j< i; j + +)              if (r[j]> r[j+ 1]) {                  pos= J;//Record interchange position                   int tmp = r[j]; r[j]=r[j+1];r[j+1]=tmp;              }           i= POS; Prepare for the next order       }   }    

  

2. The traditional bubble sort operation can only find a maximum or minimum value, we consider using the method of forward and reverse two-pass bubbling in each order to get two final values at a time (maximum and minimum), thus reducing the number of sort passes by almost half.

The improved algorithm is implemented as follows:

void bubble_2 (int r[], int n) {      int low = 0;       int high= n-1; Sets the initial value of the variable      int tmp,j;      while (Low < high) {          for (j= low; j< high; ++j)//forward bubbling, find Max              if (r[j]> r[j+1]) {                  tmp = r[j]; r[j]=r[j +1];r[j+1]=tmp;              }           --high;                 Modify the high value, move forward one for          (J=high; j>low;--j)//reverse bubble, find the smallest person              if (R[j]<r[j-1]) {                  tmp = r[j]; r[j]=r[j-1];r[ j-1]=tmp;              }          ++low;                  Modify the low value and move back one      }   }   
Quick Sort

Basic idea:

1) Select a datum element, usually select the first element or the last element,

2) The records to be sorted are divided into two separate parts, and some of the recorded elements are smaller than the datum element values. The element value of another part of the record is larger than the base value.

3) At this point the datum element is in the correct position after it is sorted

4) Then proceed to sort the two parts of the record in the same way until the entire sequence is ordered.

Examples of quick sorting:

(a) a sequencing process:

(b) The whole process of sequencing

The implementation of the algorithm:

Recursive implementations:

Package com;            public class QuickSort {public static void main (string[] args) {int a[] = {3,1,5,7,2,4,9,6,10,8};          QuickSort obj=new QuickSort ();          SYSTEM.OUT.PRINTLN ("Initial value:");          Obj.print (a);          int h=a.length-1;          Obj.quicksort (A,0,H);          System.out.println ("\ n sort after:");      Obj.print (a);                } private void QuickSort (int[] a,int Low, int. high) {if (Low

Analysis:

Fast sorting is generally considered to be the best average performance in a sorting method of the same order of magnitude (O (nlog2n)). However, if the initial sequence is ordered or basically ordered by key code, the fast sort is degenerate to bubble sort instead. In order to improve it, we usually select the Datum record by "Three take Chinese Method", and adjust the center of the two endpoint of the sorting interval and the midpoint three record key code to the pivot record. Fast sorting is an unstable sort method.


Improvements to Quick sorting

In this improved algorithm, only the sub-sequences with length greater than k are ordered quickly, the original sequence is basically ordered, and then the whole basic ordered sequence is sorted by the insertion sort algorithm. It is proved by practice that the time complexity of the improved algorithm is decreased, and the performance of the improved algorithm is the best when the K value is about 8. The algorithm idea is as follows:

void print (int a[], int n) {for (int j= 0; j<n; j + +) {Cout<<a[j] << "";  } cout<<endl;      } void Swap (int *a, int *b) {int tmp = *A;      *a = *b;  *B = tmp;                 } int partition (int a[], int low, int. high) {int privotkey = A[low];  The Datum element while (Low < high) {//From the ends of the table alternately to the middle while the low < high && A[high] >= Privotkey)--high; Search forward from the point of high, up to the low+1 position.          Switching to low-end swap (&a[low], &a[high]) is smaller than the benchmark element;          while (Low < high && A[low] <= privotkey) ++low;      Swap (&a[low], &a[high]);      } print (a,10);  return low;  } void Qsort_improve (int r[],int low,int High, int k) {if (High-Low > K) {///length is greater than k recursion, K is the specified number int Pivot = partition (R, Low, high);          The called partition algorithm remains unchanged Qsort_improve (R, Low, pivot-1,k);      Qsort_improve (R, Pivot + 1, high,k); }} void QuickSort (int r[], int n, int k) {qsort_improve (r,0,n,k);//First Call the improved algorithm qsort make it basic order//and then use the insertion sort to sort the basic ordered sequence for (int i=1; I<=n;i + +) {           int tmp = R[i];          int j=i-1;           while (TMP < R[J]) {r[j+1]=r[j]; j=j-1;      } r[j+1] = tmp;      }} int main () {int a[10] = {3,1,5,7,2,4,9,6,10,8};      cout<< "initial value:";      Print (a,10);      QuickSort (a,9,4);      cout<< "Result:";    Print (a,10);   }

  

Sorting Algorithms in Java

Related Article

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.