C# bubble sort

黄舟
Release: 2017-02-09 16:24:05
Original
1480 people have browsed it

C# Bubble sorting

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
namespace Sort  
{  
    class BubbleSorter  
    {  
        public static int[] Sort(int[] a)  
        {  
            BubbleSort(a);  
            return a;  
        }  
        private static void BubbleSort(int[] myArray)  
        {  
            for (int i = 0; i < myArray.Length; i++)//循环的趟数  
            {  
                for (int j = 0; j < myArray.Length - 1- i; j++)//每次循环的次数  
                {  
        //比较相邻元素,将值大的后移==》每一趟循环结束==》最后一个数是最大的。  
        //所以每次循环都比上一次循环的个数少1,即j < myArray.Length - 1- i  
                    if (myArray[j] > myArray[j + 1])  
                    {  
                        Swap(ref myArray[j], ref myArray[j + 1]);  
                    }  
                }  
            }  
        }  
    //引用参数与值参数  
        private static void Swap(ref int left, ref int right)  
        {  
            int temp;  
            temp = left;  
            left = right;  
            right = temp;  
        }  
    }  
}  
冒泡排序算法的运作如下:
Copy after login

The bubble sorting algorithm operates as follows:

1. Compare adjacent elements. If the first one is bigger than the second one, swap them both.

2. Do the same work for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. At this point, the last element should be the largest number. ==》The last number does not need to be compared, because it is the largest.

3. Repeat the above steps for all elements except the last one.

4. Continue to repeat the above steps for fewer and fewer elements each time until there are no pairs of numbers to compare.

The above is the content of C# bubble sorting. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
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
Popular Tutorials
More>
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!