Cocktail sort (double bubble sort, stir sort or ripple sort)

黄舟
Release: 2017-02-09 16:22:07
Original
2658 people have browsed it

Cocktail sort (double bubble sort, stir sort or ripple sort)

using System; using System.Collections.Generic; using System.Linq; using System.Text;namespace Sort { class CockTailSorter { private static int[] myArray; private static int arraySize; public static int[] Sort(int[] myArray) { arraySize = myArray.Length; CockTailSort(myArray); return myArray; } public static void CockTailSort(int[] myArray) { int low, up, index, i; low = 0;//数组起始索引 up = myArray.Length - 1;//数组索引最大值 index = low;//临时变量 //判断数组中是否有多个元素 while (up > low)//每一次进入while循环都会找出相应范围内最大最小的元素并分别放到相应的位置 { //进入该for循环会将索引限定范围内最大的元素放到最右边 for (i = low; i < up; i++)//从上向下扫描 { if (myArray[i] > myArray[i + 1]) { Swap(ref myArray[i], ref myArray[i + 1]); index = i;//记录当前索引 } } up = index;//记录最后一个交换的位置 //进入该for循环会将索引限定范围内最小的元素放到最左边 for (i = up; i > low; i--)//从最后一个交换位置从下往上扫描 { if (myArray[i] < myArray[i - 1]) { Swap(ref myArray[i], ref myArray[i - 1]); index = i; } } low = index;//记录最后一个交换的位置 } } private static void Swap(ref int left, ref int right) { int temp; temp = left; left = right; right = temp; } } }
Copy after login

Cocktail sort is a slight variation of bubble sort. The difference is that from low to high and then from high to low, bubble sort only compares each element in the sequence from low to high. It can get slightly better performance than bubble sort because bubble sort only compares in one direction (from low to high) and only moves one item in each cycle.

Using cocktail sorting, the numbers in the array are arranged irregularly. First find the smallest number and put it first, then find the largest number and put it last. Then find the second smallest number and put it in the second position, and then find the second largest number and put it in the second to last position. And so on until the sorting is completed.


The above is the content of cocktail sorting (double bubble sorting, stirring sorting or ripple sorting). For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com) !


Related labels:
c#
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!