C # Bubble sorting,

Source: Internet
Author: User

C # Bubble sorting,
Basic Principles

Compare the size of two adjacent numbers. After each comparison, place the maximum number at the end of the current round. Suppose there are Arrays: 258,445,131, 258, 445, 28, 28, the first round: And, the position does not need to be exchanged. In the second round: Comparison between 445 and 131, 445 is bigger than 131, then 445 is in the back, 131 is in the front, and so on. In the first round, the results are 258,131, 50,445, after the first round of comparison, the largest element ran to the last one. Therefore, for the second round of comparison, the last element does not need to be compared. In the second round, the comparison starts from index 0 and Index 1, but the comparison is not allowed. The algorithms are the same. The third and fourth rounds, and so on.

Code
  public class Program    {       static List<int> list = new List<int>() { 258,445,131,97,22,36,17,38,28,50 };        static void Main(string[] args)        {            int temp;            for (int i = list.Count; i > 0; i--)            {                for (int j = 0; j < i - 1; j++)                {                    if (list[j] > list[j + 1])                    {                        temp = list[j];                        list[j] = list[j + 1];                        list[j + 1] = temp;                    }                }                printlist();            }            Console.ReadLine();        }        static void printlist()        {            foreach( var s in list)            {                Console.Write(string.Format("{0}  ",s));            }            Console.WriteLine();        }    }
Output result

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.