Java Sorting Algorithm _ 002 cocktail sorting

Source: Internet
Author: User
Package WZS. sort; import Java. util. arrays; // the sort of cocktails, that is, the sort of Oriented bubbles, the sort of cocktail stirring, and the sort of stirring (which can also be considered as a kind of deformation of the sorting), // ripple sort, back-to-back or happy hour sorting is a kind of deformation of Bubble sorting. This Algorithm Different from Bubble sorting, sorting is based on bidirectional sorting in the sequence. Public class test_wzs002 {public static void main (string [] ARGs) {int [] intarray = {10, 3, 5, 7, 1, 9, 6, 2, 4, 8}; cocktailsort (intarray); system. out. println ("\ n after sorting:" + arrays. tostring (intarray);}/*** cocktail sort * @ Param intarray */Private Static void cocktailsort (INT [] intarray) {int Bottom = 0; // index start position int Top = intarray. length-1; // index end position Boolean flag = true; // control the int COUNT = 0; // number of records sorted while (FLAG) {flag = false; // from left to right, ascending order for (INT I = bottom; I <top; I ++) {If (intarray [I]> intarray [I + 1]) {swap (intarray, I, I + 1); flag = true ;}} top --; // from right to left, descending order for (Int J = top; j> bottom; j --) {If (intarray [J] <intarray [J-1]) {swap (intarray, J, J-1); flag = true ;}} bottom ++; count ++; // The end of a comparison + 1 system. out. println ("+ Count +" Times: "+ arrays. tostring (intarray ));}} /*** replace array element * @ Param intarray the specified array * @ Param I the subscript to be replaced * @ Param J The subscript replaced */Private Static void swap (INT [] intarray, int I, Int J) {int temp = intarray [I]; intarray [I] = intarray [J]; intarray [J] = temp ;}}

Output result:

 
1st sorting: [1, 3, 5, 7, 2, 9, 6, 4, 8, 10] 2nd sorting: [1, 2, 3, 5, 4, 3rd sorting: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 4th sorting: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] After sorting: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

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.