Java implements various sorting algorithms and tests sorting efficiency

Source: Internet
Author: User

Public static void bubbleSort (int a []) {
Int len = a. length;
For (int I = 0; I <len-1; I ++ ){
For (int j = 0; j <len-1-I; j ++ ){
If (a [j]> a [j + 1]) {
Int temp = a [j];
A [j] = a [j + 1];
A [j + 1] = temp;
}
}
}
}
Public static void selectSort (int a []) {
Int temp = 0;
Int len = a. length;
For (int I = 0; I <len-1; I ++ ){
Int min = a [I];
Int index = I;
For (int j = I + 1; j <len; j ++ ){
If (min> a [j]) {
Min = a [j];
Index = j;
}
}
Temp = a [I];
A [I] = a [index];
A [index] = temp;
}
}
Public static void insertSort (int a []) {
Int len = a. length;
For (int I = 1; I <len; I ++ ){
Int temp = a [I]; // the value to be inserted
Int index = I; // The position to be inserted
While (index> 0 & a [index-1]> temp ){
A [index] = a [index-1]; // assign a larger value to the position to be inserted.
Index --; // forward the position
}
A [index] = temp;
}
}
Public static int partition (int a [], int low, int height ){
Int key = a [low];
While (low While (low Height --;
A [low] = a [height];
While (low Low ++;
A [height] = a [low];
}
A [low] = key;
Return low;
}
Public static void quickSort (int a [], int low, int height ){
If (low Int result = partition (a, low, height );
QuickSort (a, low, result-1 );
QuickSort (a, result + 1, height );
}
}
Test Results
------------------------------------------
Test data: 10000
Bubble Sorting: 120 ms
Select sorting: 32 ms
Insert sorting: 20 ms
Fast sorting: 7 ms
------------------------------------------
Test data: 100000
Bubble Sorting: 13098 ms
Select sorting: 2334 ms
Insert sorting: 1264 ms
Fast sorting: 23 ms
There is a big gap in efficiency !!!!

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.