Three commonly used sorting algorithms (bubble, select, insert)

Bubble Sort

Bubble Sort
Algorithm description: Starting from the beginning (end) of the array, compare two adjacent numbers, place the largest (minimum) number at the end (head end) and loop like this, and remove the last end in the next loop (Head end) The number has been placed until the correct sequence is discharged.
Show some below c#实现.

// An highlighted block
int[] b = {
    
     15, 93, 45, 82, 16, 78, 0, 65, 32, 26 };
            for (int i = 0; i < b.Length; i++)
            {
    
    
                for (int j = 1; j < b.Length-i; j++)
                {
    
    
                    if (b[j - 1] > b[j])
                    {
    
    
                        int num = b[j];
                        b[j] = b[j - 1];
                        b[j - 1] = num;
                    }
                }
            }
            foreach (int d in b)
            {
    
    
                Console.WriteLine(d);
            }

Insertion sort

Insertion sort
Algorithm description: Start from the second number and loop to the right. In each loop, the current number is compared with the number to the left. If a number larger than the current number is found, exchange, and loop until the correct ordering is
shown below c#实现.

// An highlighted block
            int num = 0;
            int[] b = {
    
     15, 93, 45, 82, 16, 78, 0, 65, 32, 26 };
            for(int i = 1; i < b.Length; i++)
            {
    
    
                int j = i - 1;
                num = b[i];
                while (j >= 0 && num <= b[j])
                {
    
    
                    b[j + 1] = b[j];
                    j--;
                }
                b[j + 1] = num; 
            }
            foreach(int i in b)
            {
    
    
                Console.WriteLine(i);
            }

Select sort

Select sort
Algorithm description: Starting from the head end, use the intermediate variable to find the smallest number and exchange this number with the head end number. Next time the loop finds the smallest number and exchanges the second number, and so on until the correct ordering is
shown below c#实现.

// An highlighted block
            int[] b = {
    
     15, 93, 45, 82, 16, 78, 0, 65, 32, 26 };
            for(int i = 0;i < b.Length - 1; i++)
            {
    
    
                int num = i;//存储最小数值的索引
                for(int j = i+1;j < b.Length; j++)
                {
    
    
                    if (b[num]>b[j])//用当前数字与后面的每个数字比较
                    {
    
    
                        num = j;//如果当前数字比后面数字大   则交换索引
                    }
                }
                int num1 = b[num];//将最小的数与第一个数字交换
                b[num] = b[i];
                b[i] = num1;
            }
            foreach(int i in b)
            {
    
    
                Console.WriteLine(i);
            }

Guess you like

Origin blog.csdn.net/m0_47605113/article/details/108781927